Vigenère shifts each letter by the next letter of a key word, so the same plain letter can turn into different cipher letters.
What to build
Encrypt or decrypt lines of text with a Vigenère key.
Requirements
- Key letters give the shifts: A or a is 0, B or b is 1, …, Z or z is 25. Ignore any character in the key that is not a letter.
- Only letters use up a key letter; spaces and punctuation are copied and do not move the key on.
- The key starts again at its first letter on every new line.
- Keep each letter's case.
Input
Line 1: encrypt or decrypt. Line 2: the key. Each following line: the text.
Output
Each line, encrypted or decrypted.
Constraints
The key has 1 to 30 letters. 1 to 20 lines of up to 200 characters.
Example
Input:
encrypt
LEMON
ATTACK AT DAWN
Output:
LXFOPV EF RNHR
Why it works
Decrypting a letter is encrypting it with the negative shift, so one function with a direction of +1 or −1 does both, and keeping the key position in a counter that moves only on letters matches the cipher's rule.
Examples
encrypt LEMON ATTACK AT DAWN
LXFOPV EF RNHR
decrypt LEMON LXFOPV EF RNHR
ATTACK AT DAWN
Hints
Hint 1
Turn the key into an array of shifts first: "LEMON" gives [11, 4, 12, 14, 13].
Hint 2
Keep a counter k; use shifts[k % shifts.length], and add 1 only when you have shifted a letter.
Solution
Show one correct solution (try it yourself first)
const direction = prompt().trim() === "decrypt" ? -1 : 1;
const shifts = [...prompt().toUpperCase()].filter((c) => c >= "A" && c <= "Z").map((c) => c.charCodeAt(0) - 65);
const move = (ch, base, s) => String.fromCharCode(((((ch.charCodeAt(0) - base + s) % 26) + 26) % 26) + base);
let line = prompt();
while (line !== null) {
let out = "";
let k = 0;
for (const ch of line) {
const isUpper = ch >= "A" && ch <= "Z";
const isLower = ch >= "a" && ch <= "z";
if (isUpper || isLower) {
out += move(ch, isUpper ? 65 : 97, shifts[k % shifts.length] * direction);
k++;
} else out += ch;
}
console.log(out);
line = prompt();
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step