DEV Community

Small Web Tools Notes
Small Web Tools Notes

Posted on

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, 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"
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)