Skip to content

Instantly share code, notes, and snippets.

@rd13
Created November 8, 2013 15:01
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 rd13/7372240 to your computer and use it in GitHub Desktop.
Save rd13/7372240 to your computer and use it in GitHub Desktop.
Enigma Javascript
;'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