Implementing a Caesar Cipher in JavaScript (and Why You Shouldn't Use It)
A Caesar cipher is the classic first crypto exercise. Here's a clean implementation and the lessons hidden in it. function caesar(text, shift) { const s = ((shift % 26) + 26) % 26; return text.replace(/[a-z]/gi, c
A Caesar cipher is the classic first crypto exercise. Here's a clean implementation and the lessons hidden in it.
function caesar(text, shift) {
const s = ((shift % 26) + 26) % 26;
return text.replace(/[a-z]/gi, ch => {
const base = ch <= 'Z' ? 65 : 97;
return String.fromCharCode((ch.charCodeAt(0) - base + s) % 26 + base);
});
}
caesar('Hello, World', 3); // "Khoor, Zruog"
caesar('Khoor, Zruog', -3); // "Hello, World"
Gotcha 1: % in JS keeps the sign, so negative shifts need the ((n % 26) + 26) % 26 trick.
Gotcha 2: decide what to do with non-letters (here they pass through).
Breaking it:
const all = [...Array(26).keys()].map(k => caesar(ct, -k));
Score each candidate by English letter frequency and pick the best — that's frequency analysis in ten lines.
Takeaway: never roll your own crypto; use Web Crypto (crypto.subtle) with AES-GCM.
If you want a reference to check output against, caesarcipher.org has an in-browser Caesar tool and frequency analysis.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.