Artem's blog

Mainly .NET (C#, ASP.NET) and my projects

Archives for Java Script

Get Hash Code with Java Script

Once, I wrote about hash function that I improved. Though, that was C#. In this post I will show you how to get hash code with Java Script. (previous post)

function getStableHash(input,hashLength)
{
	/* Copyright (C) 2012 Artem Los,
	 * All rights reserved.
	 *
	 * code based on:
	 * http://blog.clizware.net/news/631
	 *
	 * originaly from: http://stackoverflow.com/questions/548158/fixed-length-numeric-hash-code-from-variable-length-string-in-c-sharp
	 */	

	 var _length = Math.pow(10,hashLength); //result in 10 numbers, if hashLength is 10
	 var hash = 0;

	 for (var j = 0; j < input.length; j++)
	 {
		 hash += input.charCodeAt(j);
		 hash += (hash << 10);
		 hash ^= (hash >> 6);
	 }

	 hash += (hash << 3);
	 hash ^= (hash >> 11);
	 hash += (hash << 15);

	 var result = ((hash % _length) + _length) % _length;//hash.mod(_length)

	 var check = parseInt(_length / result);
	 if (check > 1)
	 {
		 result *= check;
	 }

	 return result;
}

In order to calculate a hash value, you need to define two main variables. First of all, the string to calculate hash from (input), and eventually, the length of the result (hashLength). It is recommended that you set the hashLength to 8 or in some cases 10.

Please take a look at this code in work http://editor.clizware.net/?id=9

The right modulo

Recently, I’ve published an article here about the modular operator, and its defect. I’m not quite sure if the content is  hundred pro cents right, though. The previous post was about an encryption in Java Script, where I’ve used a certain function to get the modulo.

Number.prototype.mod = function(n) {
return ((this%n)+n)%n;
}

The prototype above is solving the entire problem. By writing a number, ex, “5.mod(3)” you will perform an modular operation 5 mod 3. The code itself is from http://javascript.about.com/od/problemsolving/a/modulobug.htm where you also might read more about that particular issue.

To see the code in work, please view this example: http://editor.clizware.net/?id=7

Tip of this weekend (25/2-12)

Another good method to encrypt ASCII based text. To view this example in work, http://editor.clizware.net/?id=7 (remember to press compile)

//Copyright (C) 2012 Artem Los, All rights reserved

function mod_c(text,key,enc_dec)
{
	//only for 128 ascii values
	if (key == "")
	{
		return "Error: no key given";
	}
	if (enc_dec === true)
	{
		var result = "";

		for (var i=0; i < text.length; i++)
		{
			result += String.fromCharCode( (text.charCodeAt(i) + key.charCodeAt(i % key.length)).mod(128)    );
		}
		return result;
	}
	else if(enc_dec === false)
	{
		var result = "";

		for (var i=0; i < text.length; i++)
		{
			result += String.fromCharCode( (text.charCodeAt(i) - key.charCodeAt(i % key.length)).mod(128)  );
		}
		return result;
	}
	else
	{
		return "Error: enc_dec is not given";
	}
}

Number.prototype.mod = function(n) {
return ((this%n)+n)%n;
}

Encrypting a website

EDIT: Please check out the updated version of this article.

When encrypting a website, we need to understand the way a browser interprets our input, i.e. html/javascript. In this case, we can produce code that is only readable by a browser.

There are several ways to encrypt a page, the main idea behind all methods is it to convert a human-readable code to ONLY computer-readable one.

    • By HTML only
    • By JavaScript
      • Using hexadecimal values
      • Using “escape/unescape”
      • Using an advanced algarithm

By HTML Only
In HTML, all letters(chars) can be written in a ASCII form, i.e., if we have a small “a” that is to be converted, we simply look up its ASCII value and write it instead of the actual char: &#97;, and so on.To sum up, the prefix is “&#”, then the ASCII code, and lastly a semicolon, “;”.

function encToASCII(_text)
{
	var _newText="";

	for(var i=0; i < _text.length;i++)
	{
		_newText += "&#" + _text.charCodeAt(i) + ";";
	}

	return _newText;
}

 

By JavaScript
JavaScript website encryption can be divided into several parts. One way is by using the hexadecimal value of a char, and write it instead of the actual char. We have to use JavaScript to perform this action, as it is shown below:

function encToHex(_text)
{
	var _newText="";
	for (var i=0; i < _text.length; i++)
	{
		_newText += "%" + decimalToHex(_text.charCodeAt(i));
	}
	return _newText;
}
function decimalToHex(_num)
{
	return _num.toString(16);
}

This method will only encrypt the given text, though, but, the user has to be able to see the encrypted text as a result (the browser won’t understand this code unless we have a function that will interpret it). This method is based on JavaScript, and we therefore need to use JavaScript to decrypt. Let us say that we encrypt “Hello World!”, which results “%48%65%6c%6c%6f%20%57%6f%72%6c%64%21”. As you might see, the prefix is “%”, and then the hexadecimal number. If the result above is our webpage, the source of that webpage should look similar to the example below:

<script type="text/javascript">
document.write(unescape("%48%65%6c%6c%6f%20%57%6f%72%6c%64%21"));
</script>
NOTE: There is a big difference between the HTML Only encryption and JavaScript encryption. For example, if you encrypt your whole page with HTML Only encryption, including “tags”, the result in the web-browser will be the source of the page. Encoding “<p>Hi</p>” will result “<p>Hi</p>”. However, by using JavaScript, the result will be executed, as a normal page would. Encoding “<p>Hi</p>” will result “Hi”.


There is also, as you might see, an opportunity to use functions escape and unescape as they are. Their actual usage is to encode/decode the url, i.e., replacing spaces, “special chars.” to url friendly one. All letters and numbers will stay the same, they will not be changed.

document.write(escape("Hello World!"));

The result you will get is Hello%20World%21. It replaces spaces with %20, and “!” with %21. Both of them are special characters(chars).

Unescape function will decode to a normal string.

document.write(unescape("Hello%20World%21"));

 

By JavaScript – Advanced algorithm
It took a while for me to define what an advanced algorithm in our case would be. I would say that the more advanced algorithm you have, the more time it takes to “crack it”. The method that will be described in this section of the post is my own little version of advanced algorithm. The method is using a logical operation, called XOR. If you already now what that is, jump to the next section.XOR is an operator, and works at a binary level. A definition in words is that the first or second value is true, but not both. Truth table shown below: 

Input Output
A B
0 0 0
0 1 1
1 0 1
1 1 0
XOR Truth table

An operation, 5 XOR 6, would result 3. The thing is, if we take either 5 XOR 3 = 6 or 6 XOR 3 = 5, we always return to our previous numbers. Conclusion, if two numbers are known, we always will get the third one.

As you might see, the decimal value 5 corresponds to 101; 6 corresponds to 110; 3 corresponds to 011.
1 0 1
1 1 0
1 1 0

By using XOR operation, we might, for instance, set a secret number, or a series of numbers, which always will return our third number. In this post, we will go though how to use a series of numbers, but also how to do it with only one number.

function en_doc(t,k)
{
	var a;
	var b;
	var r=new Array();
	for (var i=0; i<t.length ;i++)
	{
		a=t.charCodeAt(i);
		b=k.charAt(i%k.length);
		a^=b;
		r[i]=String.fromCharCode(a);
	}
	return r.join("");
}

The code shown above is my own advanced algorithm. First, we declare “a”, which is a char at certain place in string t; and b, which is a digit at certain place in k. The text to encrypt is placed in t (all chars), and the key to encrypt with is placed in k (only digits). The variable r is an array of the result/output.

First of all, we assign a to the char code at i. The variable b is then assigned to the char at i mod the length of key.

The reason why I put  a modular operation there is simple. If the key length we use is smaller than the text length, we will not be able to encrypt the whole string without it. When we are encrypting something, the key has to be of the same length as the text. By using a modular operation, even if the key is smaller than the text, it will be repeated. For example, if the key is 567 (key length=3), and the text length is 6, the output key will result 567567.

Secondly, an logical operation is executed. In other words, variable a equals to itself XOR b. Variable a has therefore a new value which is later assigned to r[i], i.e., a place in the array r which corresponds to the index value i.

Lastly, we join our array without some joining char, and that will be our encoded text. To decrypt, use the same function; place your encrypted text in t, and the key in k.

You can, however, remove this key opportunity, or as I previously defined it, using a key series,  to a single key digit. You might still use this method, but only having a key, for instance, 6, or, you might remove it at all, and set the secret digit inside the function.

If you want to include this code in your project without typing the code above, include this code before all scripts (see this code in action):

Source 1:

<script src="https://dev.clizware.net/lib/scrypto1.js"></script>

Source 2:

<script src="https://clizware.webs.com/lib/scrypto1.js"></script>

I hope this article was useful, and that you hopefully have learned something new! Below you find some useful links:

Encrypter – (for html only encryption)
http://www.iwebtool.com/html_encrypter – (encrypting to hexadecimal values, javascript)
Bitwise Operators – (about logical operators)
Escape and Unescape
Eval – (advanced encryption, etc.)

This article was revised 17.03.2013.

Tip of 22 December

In this thread I will show you two good Java Script functions. With both of them you can calculate how many chars you have.

The first one will calculate a specific element.

function calcspec(element)
{
	if (element.innerHTML != "")  // this function must be first!
	{
		return element.innerHTML.length;
	}

	if (element.value.length > 0)
	{
		return element.value.length;
	}
}

 

The second one will calculate all chars between HTML tags. HTML tags are not included.

function calcall(tag)
{
	return document.documentElement.innerHTML.length;
}

or

function calchtml()
{
	return document.getElementsByTagName("html")[0].innerHTML.length;
}

 

You might however replace innerHTML to outerHTML as shown bellow. This will therefore calculate all document. (does not work in Firefox)

function calcall(tag)
{
	return document.documentElement.outerHTML.length;
}
function calchtml()
{
	return document.getElementsByTagName("html")[0].outerHTML.length;
}

Another example of an encryption algorithm [JS]

In this post I will go through a simple encryption method I’ve done few years ago. It is actually so simple, but I’ve heard that some currently-used encryption algorithms are based on this principle.

Here is the code: (function “ec_t” – encryption method; function “dc_t” – decryption method)

/*
 * Sample encryption and
 * decryption by Artem Los
 * 
 */ 

  //Encrypt
    function ec_t(t, key) {
        var c = "";
        var d = "";
        var _key2 = StringToAsc(key);
        var e = genKey(_key2 , t.length);
        var _keyA =  new String (key.length);

        for (i = 0; i < t.length; i++) {

            var _def_t = eval(t.charCodeAt(i));
            var _def_e = eval(e.charAt(i));
            var _def_a = eval(_keyA.charAt(0));

            c = _def_e + _def_t +_def_a;
            d += String.fromCharCode (c);

        }
        return d;
    }

    function genKey(key, l) {
        var _vectorA = key;
        while (_vectorA.length < l) {
            _vectorA += _vectorA;
        }
        return _vectorA;
    }
    function StringToAsc(text) {
        var _vectorA = "";

        for (i = 0; i < text.length; i++) {
            _vectorA +=  text.charCodeAt(i);
        }
        return _vectorA;
    }

    //Decrypt
    function dc_t(t, key) {
        var c = "";
        var d = "";
        var _key2 = StringToAsc(key);
        var _keyA = new String(key.length);
        var e = genKey(_key2, t.length);

        for (i = 0; i < t.length; i++) {

            c = t.charCodeAt(i) - e.charAt(i) - _keyA.charAt (0);
            d +=  String.fromCharCode (c);
        }
        return d;

    }

    function do_e() {

        var _vecB = unescape (  in01.value);
        var _passA = pass.value;

        if (_passA != "") {
            if (ra01.checked == true) {
                var _vecC = ec_t(_vecB, _passA );
                in02.value = escape ( _vecC);
            }

            else {
                    var _vecC = dc_t(_vecB , _passA);
                    in02.value = _vecC;
            }
        }
    }

If you want to view this code in-work, enter the link below:
Encrypter

Why and how did it work?
The code above works on a simple principle, I discovered it without looking at internet, though! 😛

Say we have a table where all letters have an id, i.e., a number. The table looks as follows: A-1, B-2, C-3 …
First of all, we need to define our message, say we have “BAC” corresponding to “213”.
Then we need a key, say “CBA” – “321”. (it is in the same format as the message).

B(2) A(1) C(3)
C(3) B(2) A(1)
D(4) C(3) E(5)

The result is therefore 435 or DCE. When we decrypt we have to do the same but backwards, using the key, i.e., instead of addition use subtraction.

This is done with function “ec_t” and “dc_t”.
If the message is longer than the key, then we need to duplicate the key so it matches the message length. All that is done in function “getKey”.

It is better that you use function “do_e” instead of “ec_t”, because then all letters will go through a escape function, which means that the text will be more copy-friendly, i.e., easier to copy without missing some letters which can affect the result.

Good luck!

Tips of 23 November [JS]

So, today I will show some useful codes that might be used for protecting information with Java Script.

1. First of all, the most common protection method is to disable the right-clicking, i.e. disallow user to copy stuff from a webpage.

   
   /*
    * This script is create by Artem Los
    * Copyright (C) Artem Los, All rights reserved
    * You may use this code in commercial and
    * personal usage. You have no rights to
    * sell this code.
    * NOTE: Author must have credits for this code.
    */

    var r = "True";
    var text = "This site is protected!";

function IE(e) {
    if (navigator.appName == "Microsoft Internet Explorer") {
        if (event.button == "2" || event.button == "3") {
             alert(text);
             return false;
          }
     }
}
function NS(e) {
    if (document.layers || document.getElementById && !document.all) {
        if (e.which == "2" || e.which == "3") {
            alert(text);
        }
        else if (e.which == "1") {
        if (r == "True") { return false; }
        }
    }
    return false;
}

document.onselectstart = new Function('if(r=="True"){return false;}');document.onmousedown = IE;document.onmouseup = NS;document.oncontextmenu = new Function("return false");

So, by using the code above you can be ensured that your information is safe at a basic level. It can still be taken by looking at the source, and copying it therefrom.
I will try to publish another code that actually protects the whole website, but remember that even though you got your page encrypted, it might still be cracked. Like with all kinds of protections, it is all about the time!

2. Another tip that I will talk about is links. It is so often that robots takes the, for instance, email address, and use it for spamming. However, we may solve this issue! Here I’ve got to methods that may help you to protect your links.

 /*
    * This script is create by Artem Los
    * Copyright (C) Artem Los, All rights reserved
    * You may use this code in commercial and
    * personal usage. You have no rights to
    * sell this code.
    * NOTE: Author must have credits for this code.
    */

    var AllLinks = new Array();
    AllLinks[0] = "http://www.clizware.net/";
function email(x) {

    if (x != "" || "undefined") {
        window.location = AllLinks [x];
        var a = document.getElementById("elink" + x);

    }
    else {
        alert("This link does not exist!");
    }

In the body of the page, enter:

<a href ="#" onclick ="email(0);" id="elink1">Link</a>

To improve this code, you can for example encrypt the link. I would recommend the escape/unescape function, but It actually does not matter. Once again, it’s all about the time.

The second method is not so useful, though. It is only working in Internet Explorer, and it have actually now function, just to hide the status bar.

   /*
    * This script is create by Artem Los
    * Copyright (C) Artem Los, All rights reserved
    * You may use this code in commercial and
    * personal usage. You have no rights to
    * sell this code.
    * NOTE: Author must have credits for this code.
    */

    window.defaultStatus = "All links are protected";

Straddling Checkerboard [Java Script]

This tutorial will show you how you can encrypt/decrypt text (string) with Java Script or JScript.

First we need a table, even called for matrix. To create a matrix I chose to combine three array-lists into one single. (Note that it also works without the combining of arrays!)

        //generating 3 arrays
        var _matrixA = new Array();
        var _matrixB = new Array();
        var _matrixC = new Array();
        var _mA, _mB;

        _matrixA = new Array("A", "", "", "B", "C", "D", "E", "F", "G", "H");   // 0
        _matrixB = new Array("I", "J", "K", "L", "M", "N", "O", "P", "Q", "R"); // 1
        _matrixC = new Array("S", "T", "U", "V", "W", "X", "Y", "Z", ".", "/"); // 2

        //assign values of columns
        _mA = 1;
        _mB = 2;

        //combining matrix
        var _matrix = new Array(_matrixA, _matrixB, _matrixC); //this is the table, to get data, use _matrix[x][y]

Encryption Method:

        // Encryption method
        function encrypt(_text) {
        	var _returnVal = "";
            for (i = 0; i < _text.length; i++) {

                if (_matrixA.indexOf(_text.charAt(i)) != -1) {

                    _returnVal += (_matrixA.indexOf(_text.charAt(i)));

                }
                if (_matrixB.indexOf(_text.charAt(i)) != -1) {
                    _returnVal += (_mA); //default 1
                    _returnVal += (_matrixB.indexOf(_text.charAt(i)));

                }
                if (_matrixC.indexOf(_text.charAt(i)) != -1) {
                    _returnVal += (_mB); //default 2
                    _returnVal += (_matrixC.indexOf(_text.charAt(i)));

                }

            }
            return _returnVal;

        }

Decryption Method:

        // Decryption Method
        function decrypt(_text)
        {
        	var _returnVal = "";
        	for (i=0; i < _text.length; i++)
        	{
        		if (_text.charAt(i) != _mA || _text.charAt(i) != _mB )//the char has to be in 'first' matrix, _matrixA
        		{
        			_returnVal += _matrixA[_text.charAt(i)];
        		}

        		if (_text.charAt(i) == _mA) //the char has to be in 'secend' matrix, _matrixB
        		{
        			i++;
        			_returnVal += _matrixB[_text.charAt(i)];
        		}

        		if (_text.charAt(i) == _mB) //the char has to be in 'third' matrix, _matrixC
        		{
        			i++;
        			_returnVal += _matrixC[_text.charAt(i)];
        		}

        	}

        	return _returnVal;
        }

Copyright (C) 2011 Artem Los