Skip to content

Instantly share code, notes, and snippets.

@nacholibre
Created June 2, 2015 20:13
Show Gist options
  • Save nacholibre/9d8d5991ae880dbdb2ea to your computer and use it in GitHub Desktop.
Save nacholibre/9d8d5991ae880dbdb2ea to your computer and use it in GitHub Desktop.
decrypt
'use strict';
function joinParts(str) {
var splitAt = Math.floor(str.length/2);
var left = str.substr(0, splitAt);
var right = str.substr(splitAt);
return right + left;
}
function mod(n, m) {
return ((n % m) + m) % m;
}
function parseMessage(message) {
message = joinParts(message);
var splitted = message.split('~');
var alphabetLength = parseInt(splitted[0]);
var encryptedMessage = splitted[1];
var keyLength = parseInt(splitted[2]);
var alphabet = encryptedMessage.substr(0, alphabetLength);
var key = encryptedMessage.substr(keyLength*-1);
var msg = encryptedMessage.substr(alphabetLength, encryptedMessage.length - (keyLength + alphabetLength));
return {
'alphabet': alphabet,
'alphabetLength': alphabetLength,
'key': key,
'keyLength': keyLength,
'message': msg
};
}
function decryptMessage(msg) {
msg = msg.trim();
var parsed = parseMessage(msg);
var msgArr = parsed.message.split('');
var keyPos = 0;
var realMessage = '';
for(var i = 0; i < msgArr.length; i++) {
var currentKeyChar = parsed.key[keyPos];
var currentMessageChar = parsed.message[i];
var keyAlphabetIndex = parsed.alphabet.indexOf(currentKeyChar);
var messageAlphabetIndex = parsed.alphabet.indexOf(currentMessageChar);
var indexesSum = (messageAlphabetIndex - keyAlphabetIndex);
var realCharPos = mod(indexesSum, parsed.alphabetLength);
var realChar = parsed.alphabet[realCharPos];
realMessage = realMessage += realChar;
keyPos++;
if (keyPos === parsed.key.length) {
keyPos = 0;
}
}
return realMessage;
}
var stdinData = '';
process.stdin.on('readable', function() {
var chunk = process.stdin.read();
if (chunk !== null) {
stdinData = stdinData + chunk;
} else {
console.log(decryptMessage(stdinData));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment