Created
November 26, 2018 13:51
-
-
Save 42tg/54de5f53999e45f5982dba15d37c8a53 to your computer and use it in GitHub Desktop.
Quick encrypt and decrypt methods für vigenere ciper
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
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