Lesson 1 of 15

Caesar Cipher

Caesar Cipher

The Caesar cipher is one of the oldest and simplest encryption techniques, named after Julius Caesar who reportedly used it to protect his military communications. It is a substitution cipher where each letter in the plaintext is shifted a fixed number of positions down the alphabet.

Encryption

For a shift of kk, each letter at position pp (0-indexed, A=0, B=1, …, Z=25) becomes:

c=(p+k)mod26c = (p + k) \bmod 26

Decryption

Decryption simply shifts in the opposite direction:

p=(ck)mod26p = (c - k) \bmod 26

Example (shift = 3)

PlaintextHELLO
Shift +3KHOOR
  • HELLOKHOOR

ROT13

A special case with k=13k = 13: since 13+13=2613 + 13 = 26, encryption and decryption are the same operation. ROT13 is its own inverse.

Security

The Caesar cipher has only 26 possible keys (0–25) and is trivially broken by brute force or frequency analysis — the letter distribution of English is preserved.

Your Task

Implement:

  • caesar_encrypt(text, shift) — shift each alpha character by shift positions, preserving case and leaving non-alpha characters unchanged
  • caesar_decrypt(text, shift) — reverse the shift
Python runtime loading...
Loading...
Click "Run" to execute your code.