@guy

A blog on technology and web culture

Guy Malachi


Source CodeJavaScript XOR Encryption

This code is the basic code that is used in the protect email address from spam tool.

Use this form for encrypting and decrypting strings using XOR.

If you get a JavaScript error when you click on "Encrypt" then try changing the "XOR Key" to a different number.
XOR Key:
String to encrypt:
Encrypted string:  

This works on the basic mathematical principle that if
a XOR b equals c
then
c XOR a equals b.

So what happens here is that a is the XOR key (or the secret password) and b is the string that we want to encrypt.
In order to encrypt our string (b) then we convert all the characters in b to character codes (using the JavaScript charCodeAt function) and XOR them with the XOR key (a).
This gives us a number that we convert back to characters using the JavaScript fromCharCode function.
Now we have a string of characters that is the scrambled result of our string with the XOR key.

In order to decrypt our scrambled string all we need is the XOR key (our secret password).
First we convert each character in the scrambled string into character codes (again with the charCodeAt function) and we XOR the result with our XOR key.
Again this gives us a number that we convert back into the original character by using the JavaScript fromCharCode function.

That's it, we now have our original string back.

One note: since we don't know what characters we're going to get in the encrypted string (since the characters are the result of the XOR interpreted as characters) we may get JavaScript errors during the encryption (if the XOR result gives us a number that when converted to a character is something that JavaScript has a problem with).

If you get a JavaScript error during the encryption then just change your XOR key and try again.

Update: I just found out that this is basically an implementation of the Vernam cipher which is based on the same principles.

If you find this useful then I'd appreciate it if you .
© 2011 Guy Malachi atguy.com, All Rights Reserved