Forked from pavlos-io/XOR String Encryption with non static key
Created
May 17, 2019 10:41
-
-
Save sachinsharma/894f1488e40d38ec4621d65633b795a0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var alphabet = 'abcdefghijklmnopqrstuvwxyz', | |
shipher = [], | |
key, | |
output = []; | |
function generateKey(input, string){ | |
for(var j = 0; j < input.length; j++){ | |
var numRand = Math.floor( Math.random() * (string.length-1) ); //gets a random integer between [0 - alphabet.length] | |
shipher.push( string.charAt(numRand).toUpperCase() ); //appends next char to shipher. | |
} | |
return shipher; //this is the final char array(which is gonna be our key). | |
} | |
function encryptDecrypt(input) { | |
if( !(input === output.join("")) ) //prevents generateKey() to run when decrypting, to avoid repetitions. | |
key = generateKey(input, alphabet); //get key. | |
output = []; //makes output empty, before appending to it. | |
for (var i = 0; i < input.length; i++) { | |
var charCode = input.charCodeAt(i) ^ key[i % key.length].charCodeAt(0); //XOR | |
output.push( String.fromCharCode(charCode) ); //appends encrypted/decrypted value | |
} | |
return output.join(""); | |
} | |
var encrypted = encryptDecrypt( "string to encrypt" ); | |
console.log("Encrypted: " + encrypted); | |
var decrypted = encryptDecrypt(encrypted); | |
console.log("Decrypted: " + decrypted); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment