# How to Crack the Caesar Cipher in Python

Unlock the secrets of the Caesar cipher with our Python tutorial. Learn the ins and outs of one of history's oldest codes and how to break it using modern computing power.
7 min read · Updated nov 2023 · Ethical Hacking · Python Standard Library · Cryptography

Juggling between coding languages? Let our Code Converter help. Your one-stop solution for language conversion. Start now!

In this tutorial, we’re going old school. We will learn how to crack the Caesar cipher using Python. But before we go on, what is the Caesar cipher?

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. 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. In the original Caesar cipher, Caesar used a fixed shift of 3 positions down the alphabet. This means that A would be replaced by D, B by E, and so on. 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 Implement the Caesar cipher in Python here.

## Cracking the Caesar Cipher

To implement the Caesar cipher, we must substitute characters (letters) for other characters using a given shift length (key). Similarly, when trying to crack the Caesar cipher, we only need to reverse the process for all possible keys (0-25). There are just 26 keys (alphabets), so this process can be done in milliseconds with today’s computing power.

This is precisely what we are going to achieve in this tutorial. The reason for this tutorial is to show the weakness of the Caesar cipher. It was very good and useful at its time, but these days, not very much.

So, let’s get into it! First, 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 caeser_cipher_cracker.py).

Next, we import the necessary libraries:

# Import colorama for colorful text.
from colorama import Fore, init

init()

Colorama is used to print out colorful text.

After that, let's create a function that implements the Caesar cipher. As I said, to crack the Caesar cipher is to reverse the process. Therefore, we're starting by implementing the Caesar cipher, then reversing (cracking) it in a future function:

# Define a function for Caesar cipher encryption.
def implement_caesar_cipher(text, key, decrypt=False):
# Initialize an empty string to store the result.
result = ""
# Iterate through each character in the input text.
for char in text:
# Check if the character is alphabetical.
if char.isalpha():
# Determine the shift value using the provided key (or its negation for decryption).
shift = key if not decrypt else -key
# Check if the character is lowercase
if char.islower():
# Apply the Caesar cipher encryption/decryption formula for lowercase letters.
result += chr(((ord(char) - ord('a') + shift) % 26) + ord('a'))
else:
# Apply the Caesar cipher encryption/decryption formula for uppercase letters.
result += chr(((ord(char) - ord('A') + shift) % 26) + ord('A'))
else:
# If the character is not alphabetical, keep it as is e.g. numbers, punctuation
result += char
# Return the result, which is the encrypted or decrypted text
return result

In the above function, we implemented 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.

You can modify the code to shift the numbers as well. 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, you can do that easily if you want to shift the numbers, too.

Next up, we create a function that does the actual purpose of this program - cracking the Caesar cipher. We’ll achieve that by looping through all 26 keys, getting the respective results of each key, and displaying them to the user. This way, the user can see the decrypted text or message:

# Define a function for cracking the Caesar cipher.
def crack_caesar_cipher(ciphertext):
# Iterate through all possible keys (0 to 25) as there 26 alphabets.
for key in range(26):
# Call the caesar_cipher function with the current key to decrypt the text.
decrypted_text = implement_caesar_cipher(ciphertext, key, decrypt=True)
# Print the result, showing the decrypted text for each key
print(f"{Fore.RED}Key {key}: {decrypted_text}")

Finally, we implement functionality to accept user input. i.e., we get the text to be decrypted from the user. We will also add a while loop to this functionality so that if a user wants to decrypt more than one text, they won't have to keep running the program afresh:

# Initiate a continuous loop so the program keeps running.
while True:
# Accept user input.
encrypted_text = input(f"{Fore.GREEN}[?] Please Enter the text/message to decrypt: ")
# Check if the user does not specify anything.
if not encrypted_text:
print(f"{Fore.RED}[-] Please specify the text to decrypt.")
else:
crack_caesar_cipher(encrypted_text)

We’re done! Let’s run our code:

To run this code, you need to get a Caesar cipher encrypted text. Check this tutorial out to see how to implement the Caesar cipher.

\$ python crack_ceaser_cipher.py
[?] Please Enter the text/message to decrypt: Ftq Bkftaz Oapq ue Miqeayq
Key 0: Ftq Bkftaz Oapq ue Miqeayq
Key 1: Esp Ajeszy Nzop td Lhpdzxp
Key 2: Dro Zidryx Myno sc Kgocywo
Key 3: Cqn Yhcqxw Lxmn rb Jfnbxvn
Key 4: Bpm Xgbpwv Kwlm qa Iemawum
Key 5: Aol Wfaovu Jvkl pz Hdlzvtl
Key 6: Znk Veznut Iujk oy Gckyusk
Key 7: Ymj Udymts Htij nx Fbjxtrj
Key 8: Xli Tcxlsr Gshi mw Eaiwsqi
Key 9: Wkh Sbwkrq Frgh lv Dzhvrph
Key 10: Vjg Ravjqp Eqfg ku Cyguqog
Key 11: Uif Qzuipo Dpef jt Bxftpnf
Key 12: The Python Code is Awesome <---
Key 13: Sgd Oxsgnm Bncd hr Zvdrnld
Key 14: Rfc Nwrfml Ambc gq Yucqmkc
Key 15: Qeb Mvqelk Zlab fp Xtbpljb
Key 16: Pda Lupdkj Ykza eo Wsaokia
Key 17: Ocz Ktocji Xjyz dn Vrznjhz
Key 18: Nby Jsnbih Wixy cm Uqymigy
Key 19: Max Irmahg Vhwx bl Tpxlhfx
Key 20: Lzw Hqlzgf Ugvw ak Sowkgew
Key 21: Kyv Gpkyfe Tfuv zj Rnvjfdv
Key 22: Jxu Fojxed Setu yi Qmuiecu
Key 23: Iwt Eniwdc Rdst xh Plthdbt
Key 24: Hvs Dmhvcb Qcrs wg Oksgcas
Key 25: Gur Clguba Pbqr vf Njrfbzr

Voila! We were able to get the Plain text back. The Python Code is Awesome. Indeed it is!

There you have it. In this program, we were able to crack the Caesar cipher! Pretty cool, right? You can get the complete code here.

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!

Learn also: How to Crack Hashes in Python.

Happy cracking ♥

Ready for more? Dive deeper into coding with our AI-powered Code Explainer. Don't miss it!

Sharing is caring!

### 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!