One of the simplest and oldest encryption techniques
Type of substitution cipher where each letter is shifted by a fixed number
Named after Julius Caesar who used it for military communications
Also known as shift cipher or Caesar shift
Caesar Cipher Alphabet Example
Shift = 3
Plain : a b c d e
Cipher: d e f g h
Example:
HELLO → KHOOR
Mathematical Representation:
Encryption:
E(x) = (x + k) mod 26
Decryption:
D(x) = (x - k) mod 26
Where x is letter position
Weaknesses:
Only 25 possible keys (shifts 1-25)
Extremely vulnerable to brute force attacks
Frequency analysis can easily break it
Not suitable for modern secure communications
Python Implementation
1. Encryption Function
2. Decryption Function
Practical Examples
Example 1: Basic Encryption & Decryption
Example 2: ROT13 (Very Common Variant)
💖 Support Our Work
If you find this post helpful and would like to support my work, you can send a donation via TRC-20 (USDT). Your contributions help us keep creating and sharing more valuable content.
def caesar_encrypt(text: str, shift: int) -> str:
# Define a function that takes a string (text) and an integer (shift)
# and returns an encrypted string
result = ""
# Initialize an empty string to store the encrypted result
for char in text:
# Loop through each character in the input text one by one
if char.isupper():
# Check if the character is an uppercase letter (A–Z)
result += chr((ord(char) + shift - 65) % 26 + 65)
# Convert character to ASCII using ord()
# Subtract 65 to normalize 'A' to 0
# Add the shift value
# Use modulo 26 to wrap around the alphabet
# Add 65 to return to ASCII range of uppercase letters
# Convert back to character using chr() and append to result
elif char.islower():
# Check if the character is a lowercase letter (a–z)
result += chr((ord(char) + shift - 97) % 26 + 97)
# Convert character to ASCII
# Subtract 97 to normalize 'a' to 0
# Apply the shift
# Wrap using modulo 26
# Add 97 to return to lowercase ASCII range
# Convert back to character and append
else:
# If the character is not a letter (space, number, punctuation)
result += char
# Append the character unchanged
return result
# Return the fully encrypted string
def caesar_decrypt(text: str, shift: int) -> str:
return caesar_encrypt(text, -shift) # Works perfectly in Python
text = "Hello, Caesar Cipher!"
shift = 3
encrypted = caesar_encrypt(text, shift)
print(encrypted) # Output: Khoor, Fdhvdu Flskhu!
decrypted = caesar_decrypt(encrypted, shift)
print(decrypted) # Output: Hello, Caesar Cipher!
# ROT13 = Caesar cipher with shift = 13
print(caesar_encrypt("Secret message", 13))
# Output: Frperg zrffntr
# Decrypting ROT13 is the same as encrypting again
print(caesar_encrypt("Frperg zrffntr", 13))
# Output: Secret message