But first, let me ask you a question have you ever heard of Julius Caesar? Nope, not the guy who was assassinated in Rome or the one who conquered Gaul (France). I’m talking about his secret communication method that he used to send messages without anyone else understanding them.
That’s right! The Caesar cipher is a simple substitution cipher where each letter of the plaintext message is shifted by a certain number of positions in the alphabet, and then replaced with another letter at the same position relative to the new starting point (the shift). For example, if we use a shift of 3, ‘A’ becomes ‘D’, ‘B’ becomes ‘E’, and so on.
Now that you know what it is, let’s see how we can implement this in Python! First, let’s create a function to encrypt our message using the Caesar cipher:
# Define a function to encrypt a message using the Caesar cipher
def caesar_encrypt(message, shift):
# Convert the message to uppercase and replace spaces with underscores for easier handling
message = ''.join([c if c.isalpha() else '_' for c in message.upper()])
# Initialize an empty string to store the encrypted message
result = ''
# Iterate over each character in the message and apply the shift
for char in message:
# Check if it's a letter (a-z or A-Z)
if char.isalpha():
# Calculate the new position based on the current position and the shift
# Use the ord() function to get the ASCII value of the character
# If the character is uppercase, use the ASCII value of 'A' (65) as the starting point
# If the character is lowercase, use the ASCII value of 'a' (97) as the starting point
pos = ord(char) - 65 if char.isupper() else ord(char) - 97
# Add the shift to the current position
pos += shift
# If the new position goes past 'Z' or 'z', wrap around to the beginning of the alphabet
if pos > 25:
pos -= 26
# Convert the new position back to a character and append it to the encrypted message
# Use the chr() function to convert the ASCII value back to a character
# If the original character was uppercase, add the ASCII value of 'A' (65) to get the correct character
# If the original character was lowercase, add the ASCII value of 'a' (97) to get the correct character
result += chr(pos + (char.isupper() * 65))
# Return the encrypted message
return result
As you can see, we first convert the input message to uppercase and replace spaces with underscores for easier handling. Then, we iterate over each character in the message and apply the shift using a simple formula: `pos += shift`. If we go past ‘Z’ or ‘z’, we wrap around to the beginning of the alphabet by subtracting 26 from the result (since there are only 26 letters). Finally, we convert back to a character and append it to the encrypted message.
Now let’s see how we can decrypt our messages using the same function:
def caesar_decrypt(message, shift):
# Convert message to uppercase and replace underscores with spaces for easier handling
message = ''.join([c if c.isalpha() or c == '_' else ' ' for c in message.upper().replace('_', ' ')])
# ^ Replaces any non-alphabetic characters with spaces to avoid errors in decryption
# ^ Converts the message to uppercase for consistency
# ^ Replaces underscores with spaces to handle them as regular characters
# Initialize an empty string to store the decrypted message
result = ''
# Iterate over each character in the message and apply the inverse shift (i.e., subtracting the same amount)
for char in message:
# Check if it's a letter or underscore
if char.isalpha() or char == '_':
# Calculate the new position based on the current position, the shift, and whether it's an uppercase or lowercase character
pos = ord(char) - shift
# ^ Calculates the new position by subtracting the shift from the current position
# ^ Uses the ord() function to get the ASCII value of the character
# ^ Handles both uppercase and lowercase characters by using the ASCII values for 'A' and 'a'
# If we go past 'A' or 'a', wrap around to the end of the alphabet by adding 26 to the result (since there are only 26 letters)
if pos < 65:
pos += 26
# ^ Checks if the new position is less than the ASCII value for 'A'
# ^ If so, adds 26 to the result to wrap around to the end of the alphabet
# ^ This ensures that the decrypted message stays within the range of alphabetic characters
# Convert back to a character and append it to the decrypted message
result += chr(pos)
# ^ Uses the chr() function to convert the ASCII value back to a character
# ^ Appends the character to the decrypted message
return result
# ^ Returns the decrypted message as a string
As you can see, we first convert underscores back to spaces for easier handling. Then, we iterate over each character in the message and apply the inverse shift using a similar formula: `pos -= shift`. If we go past ‘A’ or ‘a’, we wrap around to the end of the alphabet by adding 26 to the result (since there are only 26 letters). Finally, we convert back to a character and append it to the decrypted message.
And that’s it! You can now use these functions to encrypt and decrypt your messages using the Caesar cipher technique in Python. Just remember to choose a good shift value (i.e., one that is not too easy or too difficult to guess) for maximum security.