Python

Cracking Caesar Cipher Using Brute Force Attack with Python

Topic of Contents:

  1. Vulnerabilities of Caesar Cipher
  2. Writing the Caesar Cipher Bruteforce Python Program
  3. Program Workflow
  4. Cracking Caesar Cipher Python Code
  5. Proof of Concept
  6. Conclusion
  7. Frequently Asked Questions (FAQs)

Vulnerabilities of Caesar Cipher

Caesar cipher was effective in Julius Caesar’s time, but it has significant weaknesses by modern standards. One of the most glaring issues is its lack of security due to its simplicity. There are only 25 possible keys (since a key of 0 or 26 would result in the same plaintext), making it vulnerable to brute-force attacks. With modern computing power, trying all possible keys is a trivial task.

Additionally, the Caesar cipher does not account for letter frequencies. In English, certain letters occur more frequently than the others, such as “E” and “T”. A skilled cryptanalyst can use this knowledge to narrow down the possible keys, further reducing the difficulty of breaking the cipher.

Writing the Caesar Cipher Brute Force Python Program

Program Workflow:

  1. First, you need to have a text file that contains the secret message (encrypted) that you want to decode.
  2. Then, you run the program from the command line, telling it which file to use as input. For example, you might say “brute_caesar.py secret_message.txt”.
  3. The program will iterate the decryption process using the shift key from 1 to 25 because the keys of 0 and 26 refer to the same result.
  4. Once it is done decrypting with all possible keys, save the result for later investigation. By default, we define the file name for the output text as “cracked_message.txt”.
  5. Finally, open the “cracked_message.txt” and review which key value has made sense of the text.

Cracking the Caesar Cipher Python Code

1. Import the Required Library

import argparse

The code begins by importing the “argparse” library which will be used to handle the command-line arguments.

2. Define the Caesar Cipher Decryption Function

def caesar_decrypt(ciphertext, key):
    decrypted_text = ""
    for char in ciphertext:
        if char.isalpha():
            is_upper = char.isupper()
            char = char.lower()
            decrypted_char = chr(((ord(char) - ord('a') - key) % 26) + ord('a'))
            if is_upper:
                decrypted_char = decrypted_char.upper()
            decrypted_text += decrypted_char
        else:
            decryp

The “caesar_decrypt” is a function that takes two arguments: “ciphertext” (the encrypted text) and “key” (the Caesar cipher key to be used for decryption). We initialize an empty string called “decrypted_text” to store the result later. Then, we begin to iterate over each character in the ciphertext. It performs the following decryption steps for each alphabetic character in the ciphertext:

  • Check whether the character is uppercase or lowercase and convert the character to lowercase for easier manipulation.
  • Then, decrypt the character using the Caesar cipher formula: (char – key) % 26.
  • After that, convert the decrypted character back to uppercase if it was originally uppercase.
  • Lastly, append the decrypted character to the “decrypted_text” variable since the non-alphabetic characters (e.g., punctuation or spaces) are added to the “decrypted_text” without any changes.

Finally, the function returns the “decrypted_text”.

3. Define the Brute Force Decryption Function

def brute_force_caesar(input_file, output_file):
    with open(input_file, 'r') as file:
        ciphertext = file.read()

    with open(output_file, 'w') as out_file:
        for key in range(26):
            decrypted_text = caesar_decrypt(ciphertext, key)
            out_file.write(f"Key {key}:\n")
            out_file.write("#" * 80 + "\n")
            out_file.write(f"{decrypted_text}\n")
            out_file.write("#" * 80 + "\n")

The “brute_force_caesar” is a function that takes one required argument: “input_file” (the path to the input file that contains the encrypted text). It opens and reads the content of the input file and stores it in the ciphertext variable.

The code then enters a loop that iterates through all possible Caesar cipher keys from 0 to 25. For each key, it calls the “caesar_decrypt” function with the ciphertext and the current key value.
Once it is done writing each of the decryption result, it will print where the output result is saved.

4. The Main Function

def main():
    parser = argparse.ArgumentParser(description="Brute force Caesar cipher decryption")
    parser.add_argument("input_file", help="Path to the input file containing the encrypted text")
    parser.add_argument("output_file", nargs='?', default="cracked_message.txt", help="Path to the output file to save the decryption results (default: cracked_message.txt)")
    args = parser.parse_args()

    brute_force_caesar(args.input_file, args.output_file)

The main function is where the script execution starts. It sets up an argument parser using “argparse”.

Here, we define a required command-line argument named “input_file” which is the path to the input file that contains the encrypted text. It parses the command-line arguments provided when running the script. For example, “brute_caesar.py secret_message.txt”.

5. Script Execution

if __name__ == "__main__":
    main()

This conditional block ensures that the code inside it only runs when the script is executed directly, not when it’s imported as a module. It calls the main function to start the script’s execution.

Done. Here, we save the program to “brute_caesar.py”. Run the program with the help argument to show the required options:

python brute_caesar.py -h


Alt-image & caption: Caesar Cipher Bruteforce Python Program

Proof of Concept

Now, we have the incoming secret message like the following image:


Alt-image & caption: Ciphertext Message

We know for sure that it was Caesar’s cipher, but unfortunately, we don’t know the key. The only way to decrypt this message is by brute force attack. Using the Python program that we previously created, we then crack the message. The result is shown as follows:


Alt-image & caption: Proof of concept – Caesar Cipher Bruteforce Python Program

From the previous POC, we now know that this cipher is using the shift key of 24.

Try It Yourself

Download this program source code on our GitHub page at https://github.com/bimando/Caesar-Cipher-Toolkit.

Conclusion

In summary, while the Caesar cipher was effective in Julius Caesar’s era, its simplicity presents major vulnerabilities in modern times. With only 25 possible keys and no consideration of letter frequencies, it is susceptible to brute-force attacks. Our Python program exemplifies this by systematically decoding a secret message, showcasing the cipher’s weaknesses. Discover the key insights and downloadable code on our GitHub page for a deeper understanding of this classic encryption method.

Frequently Asked Questions (FAQs)

Q1: What is a brute force attack in the context of cracking the Caesar cipher?
A1: A brute force attack involves systematically trying all possible key values (1 – 25) to decrypt the Caesar cipher until the correct key is found.

Q2: How does the letter frequency analysis aid in cracking the Caesar cipher?
A2: Letter frequency analysis exploits the non-uniform distribution of letters in the English language to narrow down the possible keys during decryption.

Q3: Are there any effective countermeasures against brute force attacks on the Caesar cipher?
A3: Employing more sophisticated encryption techniques, such as those with larger key spaces and complex algorithms, can effectively mitigate the vulnerabilities associated with brute force attacks on the Caesar cipher.

About the author

BIMA FAJAR RAMADHAN

Penetration Tester with Kali Linux. Reach me on Facebook https://www.facebook.com/xbimando