Skip to content

Instantly share code, notes, and snippets.

@mhingston
Created October 6, 2016 16:32
Show Gist options
  • Save mhingston/9e7d608145381097bde949ca7558c919 to your computer and use it in GitHub Desktop.
Save mhingston/9e7d608145381097bde949ca7558c919 to your computer and use it in GitHub Desktop.
XOR encryption/decryption for the browser (IE10+)
var XOR =
{
encrypt: function(input, key)
{
input = typeof input === 'object' ? JSON.stringify(input) : input.toString();
key = typeof key === 'object' ? JSON.stringify(key) : key.toString();
var cipherText = '';
var length = input.length;
for(var i=0; i < length; i++)
{
cipherText += String.fromCharCode(input.charCodeAt(i) ^ key.charCodeAt(Math.floor(i % key.length)));
}
var encodedText = btoa(cipherText)
return encodedText;
},
decrypt: function(input, key)
{
key = typeof key === 'object' ? JSON.stringify(key) : key.toString();
var decodedText = atob(input);
var plainText = '';
var length = decodedText.length;
for(var i=0; i < length; i++)
{
plainText += String.fromCharCode(decodedText.charCodeAt(i) ^ key.charCodeAt(Math.floor(i % key.length)));
}
return plainText;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment