Skip to content
Amal Hashim
All posts
Snippet

Javascript Encrypt Decrypt

A simple XOR based encrypt and decrypt routine in JavaScript, for demonstration only.

1 min read#JavaScript#jQuery

This is a simple encryption and decryption mechanism in JavaScript. It XORs each character code with an integer key. Running the same operation twice returns the original text.

js
function Encrypt()
{
    var actual = "stringtoencrypt";
    var key = 100; //Any integer value
    var result = "";
    for (var i = 0; i < actual.length; i++)
    {
        result += String.fromCharCode(key ^ actual.charCodeAt(i));
    }
    alert(result);
}

function Decrypt()
{
    var actual = "encryptedstring";
    var key = 100; //Any integer value
    var result = "";
    for (var i = 0; i < actual.length; i++)
    {
        result += String.fromCharCode(key ^ actual.charCodeAt(i));
    }
    alert(result);
}

Note: anyone can view the source and find the real value. This example is for demonstration only.