Free video project · Beginner
Secret code machine and codebreaker 🕵️
Caesar's cipher in Python: encrypt and decrypt messages, then crack one without the key by brute force and by teaching Python to spot real English.
The code from the video
# Secret message machine
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
def encrypt(message, shift):
result = ""
for char in message.lower():
if char in ALPHABET:
position = ALPHABET.index(char)
result += ALPHABET[(position + shift) % 26]
else:
result += char
return result
def decrypt(message, shift):
return encrypt(message, -shift)
secret = encrypt("meet me at the park at noon", 3)
print(secret)
print(decrypt(secret, 3))
mystery = "esp ecpldfcp td mfctpo fyopc esp zwo zlv ecpp"
COMMON = ["the", "and", "is", "a", "to", "of", "you", "it"]
def crack(message):
best_shift = 0
best_score = 0
for shift in range(26):
words = decrypt(message, shift).split()
score = 0
for word in words:
if word in COMMON:
score += 1
if score > best_score:
best_shift = shift
best_score = score
return best_shift
shift = crack(mystery)
print("The key was", shift)
print(decrypt(mystery, shift))
Run it in your browser with nothing to install, right here on this page.
Make it your own
- Keep capital letters as capitals and leave punctuation alone.
- Switch to a keyword cipher, where each letter of a key word sets the shift.
- Score each guess by letter frequency instead of a word list.
Skills: strings, % operator, loops, functions