Editor

Python Program to Encrypt and Decrypt Text with a Caesar Cipher

Intermediate · Strings

A Caesar cipher hides a message by shifting every letter a fixed number of places along the alphabet. With a shift of 3, A becomes D, B becomes E, and X wraps round to A. Shifting back by the same amount decrypts the message.

Program

caesar_cipher.py
def caesar(text, shift):
result = ""
for ch in text:
if ch.isupper():
result += chr((ord(ch) - ord("A") + shift) % 26 + ord("A"))
elif ch.islower():
result += chr((ord(ch) - ord("a") + shift) % 26 + ord("a"))
else:
result += ch # spaces, digits and punctuation stay the same
return result
message = "Meet me at the Library, 5 pm!" # or: message = input("Enter a message: ")
shift = 3 # or: shift = int(input("Enter the shift: "))
secret = caesar(message, shift)
print("Original: ", message)
print("Encrypted:", secret)
print("Decrypted:", caesar(secret, -shift))
Output
Original:  Meet me at the Library, 5 pm!
Encrypted: Phhw ph dw wkh Oleudub, 5 sp!
Decrypted: Meet me at the Library, 5 pm!

How it works

  1. ord(ch) - ord("A") turns a capital letter into its place in the alphabet, from 0 for A to 25 for Z.
  2. Adding shift moves the letter along, and % 26 wraps past Z back to A, so X with a shift of 3 becomes A.
  3. chr(... + ord("A")) turns the new place back into a letter; small letters work the same way using ord("a").
  4. Decrypting is the same function with the shift reversed, caesar(secret, -shift), because % also wraps negative numbers correctly.
  5. A Caesar cipher is fun but not secure: there are only 25 possible shifts, as the second alternative shows by trying them all.

Other ways to write it

Using maketrans() and translate()

Using maketrans() and translate()
import string
shift = 3
plain = string.ascii_lowercase + string.ascii_uppercase
shifted = (string.ascii_lowercase[shift:] + string.ascii_lowercase[:shift]
+ string.ascii_uppercase[shift:] + string.ascii_uppercase[:shift])
encrypt = str.maketrans(plain, shifted)
decrypt = str.maketrans(shifted, plain)
secret = "Meet me at the Library".translate(encrypt)
print("Encrypted:", secret)
print("Decrypted:", secret.translate(decrypt))
Output
Encrypted: Phhw ph dw wkh Oleudub
Decrypted: Meet me at the Library

Slicing makes the shifted alphabet: the letters from d onwards, followed by a, b and c. maketrans() pairs each letter with its partner, and translate() swaps them all in one pass.

Cracking it by trying every shift

Cracking it by trying every shift
def shift_letters(text, shift):
result = ""
for ch in text:
if ch.isalpha():
base = ord("A") if ch.isupper() else ord("a")
result += chr((ord(ch) - base + shift) % 26 + base)
else:
result += ch
return result
secret = "Wkh whvw lv rq Iulgdb"
# Try every possible shift and look for the one that reads as real words
for shift in range(1, 26):
print(f"Shift {shift:2}:", shift_letters(secret, -shift))
Output
Shift  1: Vjg vguv ku qp Htkfca
Shift  2: Uif uftu jt po Gsjebz
Shift  3: The test is on Friday
Shift  4: Sgd sdrs hr nm Eqhczx
Shift  5: Rfc rcqr gq ml Dpgbyw
Shift  6: Qeb qbpq fp lk Cofaxv
Shift  7: Pda paop eo kj Bnezwu
Shift  8: Ocz ozno dn ji Amdyvt
Shift  9: Nby nymn cm ih Zlcxus
Shift 10: Max mxlm bl hg Ykbwtr
Shift 11: Lzw lwkl ak gf Xjavsq
Shift 12: Kyv kvjk zj fe Wizurp
Shift 13: Jxu juij yi ed Vhytqo
Shift 14: Iwt ithi xh dc Ugxspn
Shift 15: Hvs hsgh wg cb Tfwrom
Shift 16: Gur grfg vf ba Sevqnl
Shift 17: Ftq fqef ue az Rdupmk
Shift 18: Esp epde td zy Qctolj
Shift 19: Dro docd sc yx Pbsnki
Shift 20: Cqn cnbc rb xw Oarmjh
Shift 21: Bpm bmab qa wv Nzqlig
Shift 22: Aol alza pz vu Mypkhf
Shift 23: Znk zkyz oy ut Lxojge
Shift 24: Ymj yjxy nx ts Kwnifd
Shift 25: Xli xiwx mw sr Jvmhec

With only 25 possible shifts, anyone can try them all and spot the one that makes sense, here shift 3. Real encryption uses keys with far too many possibilities to try.

Try it yourself

Set shift to 13 and check that encrypting the encrypted message again gives back the original; this cipher is called ROT13.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises