Show contents
Chapter 1 of 6 · 15 min
Caesar and the ancient ciphers
By the end of this chapter, you'll be able to
- Explain what plaintext, ciphertext and a key are
- Encrypt and decrypt a message with the Caesar cipher in Python
- Break a Caesar cipher by trying every key
- Recognise why a small number of keys makes a cipher weak
The basic vocabulary
Before coding, three words to know:
- the plaintext: the readable message, for example
meet at 6pm; - the ciphertext: the transformed message, unreadable without the secret;
- the key: the small secret shared by Fatou and Moussa, used to encrypt and then decrypt (get the plaintext back).
An analogy: the encryption method is the model of padlock; the key is the combination. Everyone may know the padlock model, but only those with the combination can open it. Remember this idea: the secret is the key, not the method. It is called Kerckhoffs's principle, after the cryptographer who stated it in 1883.
The Caesar cipher
The Caesar cipher shifts every letter by a fixed number of positions in the alphabet. With a shift of 3, a becomes d, b becomes e, and at the end of the alphabet we wrap around to the start: z becomes c. The key is the shift.
The encrypted message. To decrypt, Moussa subtracts 3 instead of adding 3.
Text description of the animation
- We take the letters one by one.
- Each letter becomes a number: its position in the alphabet, starting from 0.
- We add the key. If we go past 25, we wrap around to the start: that is "modulo 26".
- Each new number becomes a letter again.
- The encrypted message. To decrypt, Moussa subtracts 3 instead of adding 3.
"Modulo 26" is written % 26 in Python: it is the remainder of the division by 26. For example (25 + 3) % 26 is 2, so z becomes c. Characters that are not letters (spaces, digits, punctuation) are kept as they are.
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
def caesar(text, key):
"""Shifts each letter by `key` positions. A negative key decrypts."""
result = ""
for char in text:
if char in ALPHABET:
position = ALPHABET.index(char)
result += ALPHABET[(position + key) % 26]
else:
result += char # spaces and digits stay the same
return result
message = "meet at 6pm at awa's place"
encrypted = caesar(message, 3)
print("encrypted:", encrypted)
print("decrypted:", caesar(encrypted, -3))
encrypted: phhw dw 6sp dw dzd'v sodfh
decrypted: meet at 6pm at awa's place
To decrypt, we apply the opposite shift: -3. Python handles negative numbers well with %: (1 - 3) % 26 is 24, so b goes back to y.
Breaking Caesar: trying every key
Now imagine you are the curious friend. You see wkh fdnh go by and you know (or guess) that it is a Caesar cipher. How many possible keys? Only 25 (a shift of 26 gives back the original text). You just need to try them all and read: that is a brute-force attack.
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
def caesar(text, key):
return "".join(ALPHABET[(ALPHABET.index(c) + key) % 26] if c in ALPHABET else c for c in text)
intercepted = "wkh fdnh lv klgghq xqghu wkh ehg"
for key in range(1, 26):
print(f"key {key:>2}: {caesar(intercepted, -key)}")
key 1: vjg ecmg ku jkffgp wpfgt vjg dgf
key 2: uif dblf jt ijeefo voefs uif cfe
key 3: the cake is hidden under the bed
key 4: sgd bzjd hr ghccdm tmcdq sgd adc
key 5: rfc ayic gq fgbbcl slbcp rfc zcb
key 6: qeb zxhb fp efaabk rkabo qeb yba
key 7: pda ywga eo dezzaj qjzan pda xaz
key 8: ocz xvfz dn cdyyzi piyzm ocz wzy
key 9: nby wuey cm bcxxyh ohxyl nby vyx
key 10: max vtdx bl abwwxg ngwxk max uxw
key 11: lzw uscw ak zavvwf mfvwj lzw twv
key 12: kyv trbv zj yzuuve leuvi kyv svu
key 13: jxu sqau yi xyttud kdtuh jxu rut
key 14: iwt rpzt xh wxsstc jcstg iwt qts
key 15: hvs qoys wg vwrrsb ibrsf hvs psr
key 16: gur pnxr vf uvqqra haqre gur orq
key 17: ftq omwq ue tuppqz gzpqd ftq nqp
key 18: esp nlvp td stoopy fyopc esp mpo
key 19: dro mkuo sc rsnnox exnob dro lon
key 20: cqn ljtn rb qrmmnw dwmna cqn knm
key 21: bpm kism qa pqllmv cvlmz bpm jml
key 22: aol jhrl pz opkklu bukly aol ilk
key 23: znk igqk oy nojjkt atjkx znk hkj
key 24: ymj hfpj nx mniijs zsijw ymj gji
key 25: xli geoi mw lmhhir yrhiv xli fih
Only one line makes sense, and the key jumps out. A computer does these 25 attempts in a fraction of a millisecond. That is the first big lesson: a cipher with too few possible keys protects nothing. Modern ciphers have so many keys (2128, a 39-digit number) that all the computers in the world together could not try them before the end of the Universe.
Mini-lab: Moussa's messagePython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: a Caesar that respects capital letters
The caesar function leaves capital letters alone: "Awa" becomes "Azd" with key 3, the A stays an A. Write a function full_caesar(text, key) that also shifts capital letters (keeping them as capitals), then encrypt "Meet Awa at 6pm" with key 5 and check that you get the text back with key -5.
Hint 1
char.isupper(). You can turn it lowercase with char.lower(), shift it, then turn it back to a capital with .upper().Hint 2
UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and the same position computation.Show the solution and common mistakes
LOWER = "abcdefghijklmnopqrstuvwxyz"
UPPER = LOWER.upper()
def full_caesar(text, key):
result = ""
for c in text:
if c in LOWER:
result += LOWER[(LOWER.index(c) + key) % 26]
elif c in UPPER:
result += UPPER[(UPPER.index(c) + key) % 26]
else:
result += c
return result
encrypted = full_caesar("Meet Awa at 6pm", 5)
print(encrypted)
print(full_caesar(encrypted, -5))
Rjjy Fbf fy 6ur
Meet Awa at 6pm
We handle the two alphabets separately, with the same computation. The digit 6 does not move: we could shift digits too, with a third alphabet "0123456789" and a modulo 10.
Common mistakes:
- Forgetting the
% 26:ALPHABET[25 + 5]raises anIndexErroras soon as we go pastz. - Mixing the two alphabets: looking for a capital letter in
LOWERraises aValueErrorwithindex. - Decrypting with the same key instead of its opposite: you shift twice instead of going back to the start.
Summary
- 1Encrypting turns a plaintext into a ciphertext with a key; decrypting does the reverse.
- 2The secret must be the key, never the method (Kerckhoffs's principle).
- 3The Caesar cipher shifts letters; it has only 25 keys and is broken by trying them all.
- 4A serious cipher has so many keys that it is impossible to try them all.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.