9 min read
The Caesar cipher: a mini-lab
From variables to secret messages
At the very first session, before we drew a single line with Turtle, you were pointed at a HackerRank puzzle called "password cracker". The joke was to leave it alone for now. By the end of this lesson you will have built the other side of that story: a small program that hides a message so it cannot be read at a glance, and then reveals it again.
To do that we need one idea you have already met. A string is just text stored in a variable, like message = "Happy birthday!" from the first lecture. What we did not say back then is that a string is really a sequence of characters, one letter after another, and Python lets us walk through them one by one, exactly the way a for loop walks through a range of numbers.
Turning readable text into scrambled text on purpose, so that only someone with the secret can turn it back, is called encryption. The Caesar cipher is the oldest trick in that book, named after Julius Caesar, who used it to protect his military orders.
The idea of the Caesar cipher
The rule is almost too simple. Pick a number, called the shift. Then move every letter forward in the alphabet by that many steps.
With a shift of 3, A becomes D, B becomes E, C becomes F, and so on. The word HELLO turns into KHOOR. To read it back, you move each letter the same number of steps backward.
There is only one thing to be careful about. When you run off the end of the alphabet you wrap around to the beginning. With a shift of 3, X becomes A, Y becomes B, Z becomes C. The alphabet behaves like a circle, not a straight line.
That wrap-around is the whole puzzle of writing this in code. Everything else is a loop over the characters.
Building it, one character at a time
A good habit from the functions lesson is to solve the smallest problem first. Here the smallest problem is: shift a single character. Once one letter works, a loop handles the rest.
Python gives us two helpers for this. ord("A") returns the number the computer uses for a character (65 for capital A), and chr(65) turns that number back into the character. So we can do arithmetic on letters by turning them into numbers, shifting, and turning them back.
def shift_character(ch, shift):
if ch.isalpha():
base = ord("A") if ch.isupper() else ord("a")
return chr((ord(ch) - base + shift) % 26 + base)
return ch
Read it slowly. base is the number of the first letter, A for capitals or a for small letters, so that ord(ch) - base gives us a clean position from 0 to 25 instead of a raw computer code. We add the shift, take the remainder after dividing by 26 with % 26 (that is the wrap-around), then add base back to return to real letters. Anything that is not a letter, a space or a number, is handed back unchanged.
Now the loop. Encrypting a whole message just means shifting every character and joining the results into one new string.
def encrypt(text, shift):
return "".join(shift_character(c, shift) for c in text)
Let us try it on something local.
print(encrypt("See you Saturday", 3))
# -> Vhh brx Vdwxugdb
print(encrypt("MEET AT 11", 3))
# -> PHHW DW 11
Notice that the space and the digits 11 came through untouched, exactly as the helper promised.
Lab
Open repl.it, type in the two functions above, and encrypt your own name with a shift of 5. Then hand the scrambled version and the number 5 to the person next to you and see if they can bring your name back. That handover of the secret number is the weak point of the whole system.
Decoding: shift the other way
If encrypting moves letters forward, decrypting just moves them back. The neat part is that we do not need any new code. Shifting backward by 3 is the same as shifting forward by minus 3, and the % 26 in our helper handles negative numbers correctly.
def decrypt(text, shift):
return encrypt(text, -shift)
So the full round trip looks like this:
secret = encrypt("Takohemi te sheshi", 3)
print(secret)
# -> Wdnrkhpl wh vkhvkl
print(decrypt(secret, 3))
# -> Takohemi te sheshi
The message went out scrambled and came back whole.
Here is the honest catch, and the reason this is a lab and not real security. There are only 25 useful shifts. A computer can try all of them in a blink and read the message without ever being told the number. That is why the Caesar cipher is a toy, while the encryption that protects your bank app relies on keys so large that trying them all would take longer than the age of the universe.
This is also where the throughline points forward. That opening "password cracker" puzzle was about a machine guessing secrets by trying possibilities. Later in the course you will meet PassGAN, where a modern AI learns to guess passwords the way people actually write them. The Caesar cipher is your first, friendly look at that contest between hiding a secret and uncovering it.
Before you move on, try it live below: type a message, drag the shift, and watch it scramble and come back whole, then hand the machine all 25 shifts at once and see how fast a Caesar secret falls.
Caesar cipher playground
Encrypted
Vhh brx Vdwxugdb
Decrypted back
See you Saturday✓ matches the original
All 25 shifts
Press “Try all 25” to brute-force this text, the way a computer would.
Check yourself
Work through these in your own words before moving on.
- With a shift of 1, what does the letter
Zbecome, and which line ofshift_characteris doing the work that makes that happen? - We wrote
decryptin a single line that callsencrypt. In plain language, why is shifting backward by 3 the same as shifting forward by minus 3? - If a friend sends you a Caesar-encrypted message but forgets to tell you the shift, could you still read it? Explain what you would try, and what that tells you about how safe this cipher really is.
Where this lesson comes from
Built from
- Programming in a Data World: Lecture 3 string-manipulation / Caesar-cipher slides
- Lecture 1 deck (variables and strings) and the functions/loops toolkit
alphaPlan courses are built from taught programmes rather than invented for the web. Where a claim rests on an outside standard or a reported case, it is named above so you can check it rather than take our word for it.
This course was developed by alphaPlan Center from programs delivered in partnership with the American Corners network.
Found something unclear, outdated or improvable? Suggest an improvement