Skip to content

Instantly share code, notes, and snippets.

@ritch
Created February 9, 2012 17:34
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 ritch/1781451 to your computer and use it in GitHub Desktop.
Save ritch/1781451 to your computer and use it in GitHub Desktop.
Playing around with ciphers
#!/usr/bin/env node
var operation = process.argv[process.argv.length - 1];
var allowed = '--decipher --cipher'
if(allowed.indexOf(operation) === -1) {
operation = '--cipher';
}
// let us type a string
process.stdin.resume();
process.stdin.on('data', function(data) {
process.stdin.pause();
var ops = {};
ops['--cipher'] = cipher;
ops['--decipher'] = decipher;
ops[operation].call(this, data.toString());
});
// var real = ' abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+';
var i = 0
, real = '\n'
;
while(i++ <= 512) {
var v = String.fromCharCode(i);
v && (real += v);
var vv = String.fromCharCode(1024 - i);
vv && (real += vv);
}
var original = {};
var originalChars = [];
var index = 0;
real.split('').forEach(function(letter) {
originalChars[index] = letter;
original[letter] = index;
index++;
});
function cipher(str) {
var chars = str.split('');
var result = [];
var letter;
var shift = 1;
while(letter = chars.shift()) {
var ind = original[letter] + shift;
if(ind > originalChars.length) {
ind = 0;
shift = 0;
}
shift++;
var ciphered = originalChars[ind];
result.push(ciphered);
}
process.stdout.write(result.join(''));
process.stdout.write('\n');
}
function decipher(str) {
var chars = str.split('');
var result = [];
var letter;
var shift = 1;
while(letter = chars.shift()) {
var ind = original[letter] - shift;
if(ind > originalChars.length) {
ind = 0;
shift = 0;
}
shift++;
var ciphered = originalChars[ind];
result.push(ciphered);
}
process.stdout.write(result.join(''));
process.stdout.write('\n');
}
# input
$ ./crypto
testing 123456 aaaaaaaa
ΌfΌvΕqΖ$ϋ7ψ:υ=ϙiΗjΖkΕlΔ
# output
$ ./crypto --decipher
ΌfΌvΕqΖ$ϋ7ψ:υ=ϙiΗjΖkΕlΔ
testing 123456 aaaaaaaa
# pipes
$ cat > secret.txt
hey this is secret!
^C
$ cat secret.txt
hey this is secret!
$ cat secret.txt | ./crypto
ΘfΆ"ΊkΔwϜnΈ&·lΖzΓ}ϖϬ
$ cat secret.txt | ./crypto | ./crypto --decipher
hey this is secret!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment