History
The Roman writer Suetonius reports that Julius Caesar protected his private letters by replacing each letter with the one three places further on. The method became known as the Caesar cipher. Variants with other shifts were used for centuries, and the cipher remains a classic way to introduce cryptography.
How it works
Number the letters A=0 to Z=25. To encrypt a letter with shift n, add n and wrap around at 26. To decrypt, subtract n.
E(x) = (x + n) mod 26
D(x) = (x - n) mod 26Worked examples
- HELLO with a shift of 3 gives KHOOR.
- Attack at dawn with a shift of 3 gives Dwwdfn dw gdzq.
Why it is easy to break
There are only 25 useful keys, so you can try them all, which is called brute force. You can also use frequency analysis. In English, E is the most common letter. In a long Caesar-encrypted text, the most common cipher letter probably stands for E, which immediately reveals the shift. Our Caesar cipher decoder automates this.
Related ciphers
- ROT13: a Caesar cipher with a shift of 13, which is its own inverse. See ROT13.
- Shift cipher: the same idea on any alphabet.
- Vigenere cipher: uses a keyword so that the shift changes from letter to letter, which defeats simple frequency analysis.
In code
def caesar(text, n):
out = ""
for ch in text:
if ch.isalpha() and ch.isascii():
base = ord("A") if ch.isupper() else ord("a")
out += chr((ord(ch) - base + n) % 26 + base)
else:
out += ch
return out
print(caesar("HELLO", 3)) # KHOORTry it
Use the Caesar cipher tool to encrypt and decrypt, or make a puzzle with the generator.
Try it. Encrypt, decrypt or break a Caesar cipher in your browser.