Skip to content

Instantly share code, notes, and snippets.

@thecodeboss
Last active January 14, 2018 10:29
Show Gist options
  • Save thecodeboss/62ebb3500bdbf0855f5832b731ea0aa0 to your computer and use it in GitHub Desktop.
Save thecodeboss/62ebb3500bdbf0855f5832b731ea0aa0 to your computer and use it in GitHub Desktop.
Substitution Cypher
// Converts a character to a value between 0 and 25
function toIndex(char) {
return (char.charCodeAt(0) + 26 - 97) % 26;
}
// Converts a number from 0 to 25 back into a character
function fromIndex(idx) {
return String.fromCharCode(((idx + 26) % 26) + 97);
}
function encode(message, password) {
var encoded = "";
for (var i = 0; i < message.length; i++) {
encoded += fromIndex(toIndex(message[i]) + toIndex(password[i % password.length]));
}
return encoded;
}
function decode(message, password) {
var decoded = "";
for (var i = 0; i < message.length; i++) {
decoded += fromIndex(toIndex(message[i]) - toIndex(password[i % password.length]));
}
return decoded;
}
var message = 'helloiamapandabearhowareyou';
var encoded_message = encode(message, 'teddy');
var decoded_message = decode(encoded_message, 'teddy');
console.log('Original message: ' + message);
console.log('Encoded message: ' + encoded_message);
console.log('Decoded message: ' + decoded_message);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment