How to Implement the Caesar Cipher in Python

Learn to code the Caesar cipher in Python and encrypt messages like Julius Caesar! This beginner-friendly tutorial covers the basics of one of history's earliest ciphers with step-by-step coding instructions. Dive into the world of ancient cryptography!
  · 6 min read · Updated nov 2023 · Ethical Hacking · Python Standard Library · Cryptography

Get a head start on your coding projects with our Python Code Generator. Perfect for those times when you need a quick solution. Don't wait, try it today!

In this tutorial, we’re going back in time. We’re going to see how to implement the Caesar cipher in Python. The Caesar cipher, also known as the Caesar shift or Caesar's code, is one of the oldest and simplest encryption techniques in the history of cryptography.

The Caesar cipher is named after Julius Caesar, the Roman military general and statesman who is believed to have used this method for secure communication with his officials around 58-51 BC. Julius Caesar used this cipher to protect the confidentiality of his military orders and messages. It allowed him to communicate sensitive information without being easily understood by adversaries. He's a smart guy!

The Caesar cipher is a type of substitution cipher. It involves shifting each letter in the plaintext by a fixed number of positions down or up the alphabet. This shift is known as the key. The original Caesar cipher uses a fixed shift of 3 positions down the alphabet. This means that A would be replaced by D, B by E, etc. It wraps around the alphabet, so Z becomes C with a shift of 3.

The Caesar cipher provided a basic level of security for its time, but it is relatively simple to break. With only 26 possible keys to try (since the key can be between 0 and 25), a brute-force attack can quickly reveal the plaintext (original message/text). We covered how to break Caesar ciphers here.

Without further ado, let's get coding! First of all, install Colorama:

$ pip install colorama

Open up a Python file and name it whatever you like. It’s a good practice to name it meaningfully (like, but do whatever makes you sleep well at night. As usual, we import the necessary libraries:

import sys  # The sys module for system-related operations.
from colorama import Fore, init  # Import the colorama for colored text

init()  # Initialize the colorama library for colored text.

Fore from colorama, is used to specify the color of choice (as we’ll see). I’m saying this because that’s the only thing my comments didn’t throw lights on.

Next, we create a function that implements the Caesar cipher. From the explanation provided earlier, we need to be able to get the user’s input and shift each character by a certain amount of times or characters. If it’s a non-alphabetic character (like a number), we leave it as it is. If you want to modify the code to shift numbers, be my guest. I did not do that because, if I did, it would no longer be a standard Caesar cipher. And the topic wouldn’t be justified. But from what we’re implementing in this code, if you want to shift the numbers too, you can do that easily:

def implement_caesar_cipher(message, key, decrypt=False):
   # Initialize an empty string to store the result.
   result = ""
   # Iterate through each character in the user's input message.
   for character in message:
       # Check if the character is an alphabet letter.
       if character.isalpha():
           # Determine the shift amount based. i.e the amount of times to be shifted e.g 2,3,4....
           shift = key if not decrypt else -key
           # Check if the character is a lowercase letter.
           if character.islower():
               # Apply Caesar cipher transformation for lowercase letters.
               result += chr(((ord(character) - ord('a') + shift) % 26) + ord('a'))
               # Apply Caesar cipher transformation for uppercase letters.
               result += chr(((ord(character) - ord('A') + shift) % 26) + ord('A'))
           # Preserve non-alphabet characters as they are.
           result += character
   return result  # Return the encrypted or decrypted result.

Next, we get the input from the user. We’ll be getting two inputs from the user. The first one is the text or message to be encrypted, while the second is the shift length (key) the user desires.

We’ll take a step further by ensuring that the key is between 0 and 25. That is, the messages will be shifted between 0 and 25 characters. This is because there are only 26 alphabets. By the way, setting the key to 0 means you do not want to apply any shift. It’ll remain the same as the input text:

# Prompt the user to enter the text to be encrypted
text_to_encrypt = input(f"{Fore.GREEN}[?] Please Enter your text/message: ")
# Prompt the user to specify the shift length (the key).
key = int(input(f"{Fore.GREEN}[?] Please specify the shift length: "))
# Check if the specified key is within a valid range (0 to 25).
if key > 25 or key < 0:
   # Display an error message if the key is out of range.
   print(f"{Fore.RED}[!] Your shift length should be between 0 and 25 ")
   sys.exit()  # Exit the program if the key is invalid.

Finally, we encrypt the user’s input and print the encrypted version:

# Encrypt the user's input using the specified key.
encrypted_text = implement_caesar_cipher(text_to_encrypt, key)

# Display the encrypted text.
print(f"{Fore.GREEN}[+] {text_to_encrypt} has been encrypted as {Fore.RED}{encrypted_text}")

That’s it! Now, let’s run our code:

$ python
[?] Please Enter your text/message: The Python Code
[?] Please specify the shift length: 10
[+] The Python Code has been encrypted as Dro Zidryx Myno

From a security perspective, using the Caesar cipher today, of course, is not advisable. This is because there are just 26 keys to try. And with today's computing power, Caesar ciphers can be cracked in milliseconds. You can learn how to do that here.

The Caesar cipher has several limitations, including its vulnerability to frequency analysis. In English text, certain letters, like E, appear more frequently than others, making it easier to guess the key through analysis of the ciphertext. The purpose of this demonstration is to show the historical significance of the Caesar cipher and also to tell you that It laid the foundation for more complex encryption methods. Its substitution principles are still relevant in modern cryptography.

Finally, in our Ethical Hacking with Python EBook, we've built over 39 hacking tools and scripts from scratch using Python! Check it out here if you're interested!

Check the complete code here.

Related: How to Verify File Integrity in Python.

Happy ciphering ♥

Just finished the article? Why not take your Python skills a notch higher with our Python Code Assistant? Check it out!

View Full Code Create Code for Me
Sharing is caring!

Read Also

Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!