cipher.ink Write a message

Ciphers · Classical ciphers

The substitution cipher

Scramble the alphabet and you get 26! possible keys. Counting letters still breaks it. Here's how it works, who broke it first, and how.

A simple substitution cipher swaps every letter of the alphabet for a different letter, always the same one. The key is the scrambled alphabet itself. There are 26! possible keys, about 4 × 1026, far too many to try one by one. And yet anyone with a pencil and a page of ciphertext can break it, because the swap never hides how often each letter occurs.

Try it

Nothing you type here leaves your browser.

The key can be 26 distinct letters or, more conveniently, a keyword. A keyword such as ZEBRAS goes first and the rest of the alphabet follows in order, skipping letters already used. The table under the result shows the alphabet your key produced.

How it works

plain letter on top, cipher letter below, key ZEBRAS (key letters filled)ABCDEFGHIJKLMZEBRASCDFGHIJNOPQRSTUVWXYZKLMNOPQTUVWXY
The keyword ZEBRAS gives this cipher alphabet. A becomes Z, B becomes E, C becomes B, and the letters of the keyword are filled.

To encrypt, replace each plaintext letter with the letter beneath it. Flee at once. We are discovered! becomes Siaa zq lkba. Va zoa rfpbluaoar! To decrypt, find each ciphertext letter in the lower row and read off the one above. Spaces and punctuation stay put, so the word lengths survive too, and that helps an attacker.

A random permutation is stronger than a keyword alphabet, but it's harder to remember. That's why people in the past either wrote the key down or used a keyword. The key space is the number of ways to arrange 26 letters: 26 × 25 × 24 × … × 1 = 403,291,461,126,605,635,584,000,000, written 26!, about 4.03 × 1026. A computer testing a trillion keys a second would need about 12.8 million years to try them all.

A long history, and how it ended

Substitution ciphers are very old. The Kama Sutra lists secret writing by letter substitution among the arts a woman should learn, and Julius Caesar's shift is a special case (Caesar cipher). For centuries the sheer size of the key space made them look safe. Then, around the ninth century, the Arab scholar al-Kindi described in a manuscript on deciphering messages how to count the letters. His insight was that a language has a fingerprint, and substitution doesn't change it.

The famous case is Mary, Queen of Scots. In 1586 she wrote to the conspirators of the Babington plot using a nomenclator, a substitution with extra symbols for common words and names. Thomas Phelippes, the cipher secretary of Elizabeth I's spymaster, deciphered the letters. Her approval of the plot to assassinate Elizabeth sent her to the block in February 1587.

Substitution ciphers have a place in fiction too. Edgar Allan Poe's story The Gold-Bug (1843) walks the reader through breaking one by counting symbols, and Arthur Conan Doyle's "The Adventure of the Dancing Men" (1903) does the same with stick figures standing for letters. More recently, the Zodiac killer's 408-symbol cipher of 1969, a substitution with several symbols for each common letter, was broken within days by a schoolteacher and his wife. A second, 340-symbol message went unsolved until December 2020.

Breaking it: count the letters

In English, letters occur with steady frequencies: E about 12.7% of the time, T 9.1%, A 8.2%, O 7.5%, I 7.0% and N 6.7%. A substitution cipher changes the letters but leaves the counts alone. Take a 364-letter paragraph encrypted with ZEBRAS. Its commonest ciphertext letters, with counts, are:

1st2nd3rd4th5th6th7th
Ciphertext letter and countA 52Q 33L 28Z 28O 27K 25P 24
What it stands forE 52T 33A 28O 28R 27N 25S 24

The counts are identical because the letters are the same ones, relabeled. Even on a text this short, the commonest ciphertext letter stands for E and the second for T. That's a start. Once two or three letters are fixed, more steps follow, and each one confirms the others:

  1. One-letter words are almost always a or I.
  2. Common short words such as the, and and of show up as repeating three-letter groups. Once E and T are fixed, a frequent group ending in the cipher letter for E is probably the.
  3. Double letters are mostly ll, ee, ss, oo or tt.
  4. Pattern words: a word whose letters repeat in the pattern 1-2-3-3-4 fits letter, little or pretty, and a dictionary of patterns narrows it down.

Computers do the same thing faster. A program starts with a guess at the key, scores how English the decryption looks using the frequencies of four-letter groups, swaps two letters, keeps the swap if the score rises, and repeats. This hill-climbing approach finds the key for a few hundred letters of text in a fraction of a second, even though it searches nowhere near 4 × 1026 keys.

The substitution solver on this site does the counting for you and lets you assign letters by hand.

Defenses that were tried

  • Homophones. Give common letters several symbols, so E has six ciphertext characters and Z has one. The counts flatten out. The Zodiac 408 cipher did this, and it still falls to a patient attacker because letter pairs and word patterns survive.
  • Nomenclators. Add symbols for whole words and names, as Mary's cipher did.
  • Several alphabets. Use a different substitution for each letter in turn, which leads to the Vigenère cipher.

The code

Substitution with a 26-letter key, and a helper to turn a keyword into one.

// Simple substitution: `key` is the cipher alphabet, 26 different capital letters. Key[0] stands for A, key[1] for B, ...
function substitution(text, key, decode) {
  var plain = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', from = decode ? key : plain, to = decode ? plain : key;
  return text.replace(/[a-z]/gi, function (ch) {
    var up = ch.toUpperCase(), out = to[from.indexOf(up)];
    return ch === up ? out : out.toLowerCase();
  });
}

// Make a key from a keyword: its distinct letters first, then the rest of the alphabet in order.
function keywordAlphabet(word) {
  var seen = {}, out = '';
  (word.toUpperCase().replace(/[^A-Z]/g, '') + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ').split('').forEach(function (c) {
    if (!seen[c]) { seen[c] = true; out += c; }
  });
  return out;
}

Further reading

  1. Wikipedia: Substitution cipher
  2. Singh: The Code Book, chapter 1 (publisher page)
  3. Edgar Allan Poe: The Gold-Bug (1843)
  4. Wikipedia: Zodiac Killer