Skip to content

Instantly share code, notes, and snippets.

@gialloporpora
Last active August 29, 2015 14:05
Show Gist options
  • Save gialloporpora/3dce8005d76b826beaf9 to your computer and use it in GitHub Desktop.
Save gialloporpora/3dce8005d76b826beaf9 to your computer and use it in GitHub Desktop.
This code implement the Vigenere cypher to solve EFF Puzzle (2014).
/*
This is the implementation in JS of the Vigenere cypher to solve EFF puzzle:
https://www.eff.org/deeplinks/2014/08/effs-defcon-22-t-shirt-puzzle-explained
*/
String.prototype.charOrdinalCodeAt = function(pos){
/*
This function returns this values:
* -1 if the character at position pos is not a letter;
* if the character at position pos is a letter it returns the positional value in alphabet, for lower case letter it returns its positional value + 26, for example:
* s = "Aa+";
* charOrdinalCodeAt(0) = 0
* charOrdinalCodeAt(1) = 26
* charOrdinalCodeAt(2) = -1
*/
let vc = this.charCodeAt(pos);
if ((vc<65) || (vc>122) || ((vc>90) && (vc<96))) return -1;
vc = vc -65;
if (vc>25) vc = vc - 6;
return vc;
}
String.prototype.onlyLetters = function(){
/* This function remove all non letters from a string */
return this.replace(/[^\w]/g, '');
}
vigenere = function(phrase, keyword, state){
let cypher = '';
// keyword must contains only upper case letters A-Z
keyword = keyword.onlyLetters().toUpperCase();
let j = 0; // counts character to use in keyword
for (i=0; i<phrase.length; i++){
val = phrase.charOrdinalCodeAt(i);
if (val<0) enci = phrase[i]; // when character is not a letter simply return it
else {
enci = (((val % 26) + state*keyword.charOrdinalCodeAt(j)) + 26) % 26;
enci = String.fromCharCode(enci+65);
if (val>25) enci = enci.toLowerCase();
j = (j + 1) % keyword.length;
}
cypher+=enci;
}
return cypher;
}
vigenereEnc=function(phrase, keyword){
return vigenere(phrase, keyword,1);
}
vigenereDec = function(phrase, keyword){
return vigenere(phrase, keyword, -1);
}
vigenere2 = function(phrase, keyword, state){
let cypher = '';
keyword = normalizeKeyword(phrase, keyword);
let j = 0;
for (i=0; i<phrase.length; i++){
val = valLetter(phrase[i])
if (val<0) enci = phrase[i];
else {
enci = (((val) + state*valLetter(keyword[j]))) % 52;
if (enci < 0) enci+=52;
enci = String.fromCharCode(enci+65);
if (val>25) enci = enci.toLowerCase();
j+=1 %keyword.length;
}
cypher+=enci;
}
return cypher;
}
s = "aA-";
msg = "[Iikcggu] Gvdw ag etxlku | [Ptjhafvmkx] rqgrva(cgvs urlaiaixcm Asiixl) | [Gwhusu] akksdx bzqaymoukh(gsyi, Jnsrgo) | [Rmtm] mwllzg(ihrl.qv_e? Wkivav)";
kw = "Everyone has something to hide";
alert(vigenereDec(msg,kw));
/*
* To test the encryption function I use the example on the english Wikipedia page:
* http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher
msg = "ATTACKATDAWN";
kw = "lemon";
alert(vigenereEnc(msg, kw));
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment