Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sachinsharma/894f1488e40d38ec4621d65633b795a0 to your computer and use it in GitHub Desktop.
Save sachinsharma/894f1488e40d38ec4621d65633b795a0 to your computer and use it in GitHub Desktop.
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