Created
November 8, 2013 15:01
-
-
Save rd13/7372240 to your computer and use it in GitHub Desktop.
Enigma Javascript
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
;'use strict'; | |
enigma = (function() { | |
var _rotors = [ 'EKMFLGDQVZNTOWYHXUSPAIBRCJ', | |
'AJDKSIRUXBLHWTMCQGZNPYFVOE', | |
'BDFHJLCPRTXVZNYEIWGAKMUSQO' | |
] | |
, _reflector = "YRUHQSLDPXNGOKMIEBFZCWVJAT" | |
, _alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" | |
, _key = "ABC"; | |
return { | |
crypt: function(ct) { | |
// Sets initial permutation | |
var L = li(_key[0]) | |
, M = li(_key[1]) | |
, R = li(_key[2]) | |
, output = ''; | |
for (x = 0; x < ct.length; x++) { | |
ct_letter = li(ct[x]); | |
// Step right rotor on every iteration | |
R = mod26(R + 1); | |
// Pass through rotors | |
a = _rotors[2][mod26(R + ct_letter)]; | |
b = _rotors[1][mod26(M + li(a) - R)]; | |
c = _rotors[0][mod26(L + li(b) - M)]; | |
// Pass through reflector | |
ref = _reflector[mod26(li(c) - L)]; | |
// Inverse rotor pass | |
d = mod26(_rotors[0].indexOf(_alpha[mod26(li(ref) + L)]) - L); | |
e = mod26(_rotors[1].indexOf(_alpha[mod26(d + M)]) - M); | |
f = _alpha[mod26(_rotors[2].indexOf(_alpha[mod26(e + R)]) - R)]; | |
output += f; | |
} | |
return output; | |
} | |
} | |
})(); | |
function li(l) { | |
// Letter to index | |
return "ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(l); | |
} | |
function mod26(n) { | |
// Takes into account negative modulo | |
return ((n % 26) + 26) % 26; | |
} | |
var start = new Date().getTime(); | |
var i = 1000000; | |
// do { | |
enigma.crypt('PZUFWDSASJGQGNRMAEODZJXQQKHSYGVUSGSU'); | |
// } while (i--); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment