Skip to content

Instantly share code, notes, and snippets.

@robcalcroft
Last active April 13, 2019 20:29
Show Gist options
  • Save robcalcroft/b0f1ebc9ec08480b900b273eb57b8146 to your computer and use it in GitHub Desktop.
Save robcalcroft/b0f1ebc9ec08480b900b273eb57b8146 to your computer and use it in GitHub Desktop.
A super basic character shift cipher
const alphabet = [
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z"
];
// Encrypt
function encrypt(plainText) {
const ptLength = plainText.length;
const encryptedText = [];
for (let i = 0; i < ptLength; i += 1) {
const letter = plainText.charAt(i);
const indexInAlphabet = alphabet.indexOf(letter);
let index = indexInAlphabet - 1;
if (indexInAlphabet - 1 < 0) index = 25;
encryptedText.push(alphabet[index]);
}
return encryptedText.join("");
}
// Decrypt
function decrypt(plainText) {
const ptLength = plainText.length;
const encryptedText = [];
for (let i = 0; i < ptLength; i += 1) {
const letter = plainText.charAt(i);
const indexInAlphabet = alphabet.indexOf(letter);
let index = indexInAlphabet + 1;
if (indexInAlphabet + 1 > 25) index = 0;
encryptedText.push(alphabet[index]);
}
return encryptedText.join("");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment