Skip to content

Instantly share code, notes, and snippets.

@42tg
Created November 26, 2018 13:51
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 42tg/54de5f53999e45f5982dba15d37c8a53 to your computer and use it in GitHub Desktop.
Save 42tg/54de5f53999e45f5982dba15d37c8a53 to your computer and use it in GitHub Desktop.
Quick encrypt and decrypt methods für vigenere ciper
const Alphabet = `ABCDEFGHIJKLMNOPQRSTUVWXYZ`.split("");
const isEqualWith = key => v => key === v;
const matchKeyWithText = (key, text) =>
text
.split("")
.map((_, i) => key[i % key.length])
.join("");
const decode = key => text => {
const keytext = matchKeyWithText(key, text);
let result = "";
for (let i = 0; i < text.length; i++) {
const textIndex = Alphabet.findIndex(isEqualWith(text[i]));
const keyIndex = Alphabet.findIndex(isEqualWith(keytext[i]));
let realIndex = textIndex - keyIndex;
if (realIndex < 0) realIndex += Alphabet.length;
result += Alphabet[realIndex];
}
return result;
};
const encrypt = key => text => {
const keytext = matchKeyWithText(key, text);
let result = "";
for (let i = 0; i < text.length; i++) {
const textIndex = Alphabet.findIndex(isEqualWith(text[i]));
const keyIndex = Alphabet.findIndex(isEqualWith(keytext[i]));
let realIndex = (textIndex + keyIndex) % Alphabet.length;
result += Alphabet[realIndex];
}
return result;
};
encrypt("KEY")("DCODE"); //?
decode("KEY")("NGMNI"); //?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment