Introduction
Encryption is older than computers. Two thousand years ago, Julius Caesar is said to have sent orders with every letter moved three places along the alphabet, so that A became D and B became E. Anyone who caught the messenger saw nonsense.
Old ciphers are worth learning for one reason: the way they break teaches what a modern cipher must do. Every rule in this module ("the key must be long", "patterns must not show", "the method can be public") was learned by breaking something like the ciphers in this lesson.
How it works
A cipher has two parts: the algorithm (the method) and the key (the secret setting). In the Caesar cipher the algorithm is "move each letter along the alphabet" and the key is how many places. Decrypting is the same move backwards, and % 26 wraps Z round to A.
// Caesar cipher: move every letter `shift` places along the alphabet.
function caesar(text, shift) {
let out = "";
for (const ch of text) {
const code = ch.charCodeAt(0);
if (code >= 65 && code <= 90) out += String.fromCharCode(((code - 65 + shift + 26) % 26) + 65);
else if (code >= 97 && code <= 122) out += String.fromCharCode(((code - 97 + shift + 26) % 26) + 97);
else out += ch;
}
return out;
}
const plain = "Meet me at the library";
const secret = caesar(plain, 3);
console.log(secret);
console.log(caesar(secret, -3));Try it above: type a sentence, change the shift and watch the mapping row change. Then press Break it. The playground tries all 26 shifts and ranks the results by how much they look like English. With only 26 possible keys, a computer tries them all in less time than it takes you to blink. This is a brute-force attack, and it is why a key space must be huge.
Even without a computer, a Caesar cipher falls to frequency analysis. In English, E is by far the most common letter, followed by T and A. A cipher that replaces each letter with one fixed other letter keeps those counts: if H is the most common letter in the cipher text, it probably stands for E.
The Vigenère cipher was built to beat frequency analysis. It uses a key word, such as LEMON, and shifts each letter by the next letter of the key (A means shift 0, B shift 1, and so on). Because the shift keeps changing, the same plain letter turns into different cipher letters, and the letter counts flatten out. For about three hundred years it was called "the indecipherable cipher". It is not: in the 1800s, Charles Babbage and Friedrich Kasiski found that repeated words in the plain text, falling under the same part of the key, leave repeated groups in the cipher text. The distance between repeats gives away the key length, and then each position is just a Caesar cipher with its own frequency analysis.
// Vigenère: each letter gets its own Caesar shift, taken from the next letter of the key (A = 0, B = 1, ...).
function vigenere(text, key, direction) {
let out = "";
let k = 0;
for (const ch of text) {
const code = ch.charCodeAt(0);
if (code >= 65 && code <= 90) {
const shift = (key.charCodeAt(k % key.length) - 65) * direction;
out += String.fromCharCode(((code - 65 + shift + 26) % 26) + 65);
k++;
} else {
out += ch;
}
}
return out;
}
const secret = vigenere("ATTACK AT DAWN", "LEMON", 1);
console.log(secret);
console.log(vigenere(secret, "LEMON", -1));
// The same plain letter T becomes two different cipher letters.
console.log("T -> " + secret[1] + " and " + secret[2]);Example
Here is a message intercepted from a student group chat, encrypted with an unknown Caesar shift. The program breaks it with frequency analysis alone.
// Breaking a Caesar cipher: count the letters, guess that the most common one stands for E.
const cipher = "Wkh hadp ehjlqv dw whq, vr phhw ph dw wkh vwdwlrq dw qlqh";
const counts = new Array(26).fill(0);
for (const ch of cipher.toUpperCase()) {
const k = ch.charCodeAt(0) - 65;
if (k >= 0 && k < 26) counts[k]++;
}
let most = 0;
for (let k = 1; k < 26; k++) if (counts[k] > counts[most]) most = k;
const shift = (most - 4 + 26) % 26; // 4 is the position of E
console.log("Most common letter: " + String.fromCharCode(65 + most) + " (" + counts[most] + " times)");
console.log("Guessed shift: " + shift);
let plain = "";
for (const ch of cipher) {
const code = ch.charCodeAt(0);
if (code >= 97 && code <= 122) plain += String.fromCharCode(((code - 97 - shift + 26) % 26) + 97);
else if (code >= 65 && code <= 90) plain += String.fromCharCode(((code - 65 - shift + 26) % 26) + 65);
else plain += ch;
}
console.log(plain);Line by line
countshas 26 slots, one per letter. The loop turns each letter to upper case and adds one to its slot; spaces and commas are skipped because their index is outside 0 to 25.- The second loop finds the slot with the largest count.
Happears 9 times. - If
Hstands forE, the shift is the distance from E (position 4) to H (position 7): 3. The+ 26keeps the result positive for letters before E. - The last loop moves every letter back 3 places, keeping case and leaving other characters alone, and the sentence appears.
Expected result
Most common letter: H (9 times)
Guessed shift: 3
The exam begins at ten, so meet me at the station at nine
On short messages the most common letter is not always E. A real attacker then tries T, then A, or simply checks all 26 shifts, as the playground does.
In the real world
- No one protects real data with these ciphers today. They appear in puzzles, games and lessons like this one.
- Kerckhoffs's principle (1883) says a cipher should stay secure even if everything except the key is public. AES, used today, is published in full; only the key is secret.
- "Security through obscurity" (hoping the method stays secret) fails again and again, because methods leak, get reverse-engineered or get guessed.
- The one-time pad, a Vigenère cipher whose key is truly random, as long as the message, and never reused, is provably unbreakable. It is rarely practical, because the key is as long as everything you will ever send.
Common mistakes
- Thinking a secret method is enough. If the security depends on nobody knowing how it works, it is already weak.
- Using a short key with Vigenère. A short key repeats often, which is exactly what Kasiski's method looks for.
- Reusing a one-time pad. Two messages with the same pad can be combined to cancel the key out.
- Calling encoding encryption. Base64 and ROT13 have no key at all; anyone can reverse them.
Best practices
- Never invent your own cipher for real data; use a standard, well-studied one.
- Judge a cipher by the size of its key space and the attacks against it, never by how scrambled the output looks.
- Keep the key secret and assume everything else about the system is known.
- Use old ciphers to learn how attacks work, then leave them in the classroom.
Summary
A cipher combines an algorithm with a key. The Caesar cipher has only 26 keys, so brute force breaks it at once, and frequency analysis breaks it by hand. The Vigenère cipher hides letter frequencies with a repeating key word, but the repetition itself gives the key length away. These failures gave us the rules every modern cipher follows: a huge key space, no visible patterns, and a method that can be public while the key stays secret.
Quick check
Key takeaways
- A small key space falls to brute force, so modern keys allow an astronomically large number of values.
- A cipher that keeps letter patterns can be broken by counting.
- Repeating a key leaves repeated patterns, which give the key away.
- Security must rest on the key alone; the method should be public and well studied.
Practice problems for this lesson
Was this lesson clear?
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.