Last active
January 14, 2018 10:29
-
-
Save thecodeboss/62ebb3500bdbf0855f5832b731ea0aa0 to your computer and use it in GitHub Desktop.
Substitution Cypher
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
// 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