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
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
ord(ch) - ord("A")turns a capital letter into its place in the alphabet, from 0 for A to 25 for Z.- Adding
shiftmoves the letter along, and% 26wraps past Z back to A, so X with a shift of 3 becomes A. chr(... + ord("A"))turns the new place back into a letter; small letters work the same way usingord("a").- Decrypting is the same function with the shift reversed,
caesar(secret, -shift), because%also wraps negative numbers correctly. - 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()
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises