Last active
August 29, 2015 13:56
-
-
Save riston/9124216 to your computer and use it in GitHub Desktop.
VigenèreCipher
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
function VigenèreCipher(key, abc) { | |
var keyLen = key.length, | |
abcLen = abc.length - 1, | |
abcObj, | |
abcToObject; | |
key = key.split(''); | |
abc = abc.split(''); | |
abcToObject = function (abc) { | |
var obj = {}; | |
abc.forEach(function (elem, index) { | |
obj[elem] = index; | |
}); | |
return obj; | |
} | |
abcObj = abcToObject(abc); | |
console.log(abcObj); | |
/** | |
* Encode part | |
*/ | |
this.encode = function (str) { | |
var encChars = []; | |
for (var i = 0, j = 0; i < str.length; i++) { | |
if (str[i] in abcObj) { | |
var keyCode = abcObj[key[j % keyLen]], | |
charCode = abcObj[str[i]], | |
resCode = keyCode + charCode; | |
encChars.push(abc[resCode % abcLen - 1]); | |
// console.log(key[i % keyLen], charCode, keyCode, resCode % abcLen, abc[resCode]); | |
j++; | |
} else { | |
console.log("Not in abc", str[i]); | |
encChars.push(str[i]); | |
} | |
} | |
return encChars.join(''); | |
}; | |
/** | |
* Decode part | |
*/ | |
this.decode = function (str) { | |
var deChars = []; | |
for (var i = 0, j = 0; i < str.length; i++) { | |
if (str[i] in abcObj) { | |
var keyCode = abcObj[key[j % keyLen]], | |
charCode = abcObj[str[i]], | |
resCode = charCode - keyCode; | |
if (resCode < 0) { | |
resCode += abcLen + 1; | |
} | |
deChars.push(abc[resCode % abcLen ]); | |
j++; | |
// console.log(key[i % keyLen], charCode, keyCode, resCode % 25, abc[resCode]); | |
} else { | |
deChars.push(str[i]); | |
} | |
} | |
return deChars.join(''); | |
}; | |
} | |
var abc, key; | |
abc = "abcdefghijklmnopqrstuvwxyz"; | |
key = "password" | |
c = new VigenèreCipher(key, abc); | |
console.log(c.encode('codewars') === 'rovwsoiv'); //rovwsoiv | |
console.log(c.encode('codewars')); | |
console.log(c.decode('laxxhsj')); // returns 'waffles') | |
abc = "abcdefghijklmnopqrstuvwxyz"; | |
key = "pa" | |
c = new VigenèreCipher(key, abc); | |
console.log(c.encode('l o')); | |
// console.log(c.decode('l o')); | |
// console.log(c.encode('srawedoc') === 'hrsoarff'); | |
// console.log('Last word'); | |
// console.log(c.encode('srasdsadsadsawedoc') === 'hrsoarff'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment