| by Arround The Web | No comments

Decrypting Caesar Cipher Using Python: Step-by-Step Tutorial

Topic of Contents:

  1. How the Caesar Cipher Algorithm Works
  2. Caesar Cipher Decryption
  3. Mathematical Expression of the Caesar Cipher Decryption
  4. Implementing the Caesar Cipher Decryption in Python
  5. Proof of Concept
  6. Conclusion
  7. Frequently Asked Questions (FAQs)

How the Caesar Cipher Algorithm Works

The Caesar cipher is a simple substitution cipher that involves shifting each letter of the plaintext that is fixed in three number positions forward in the alphabet to generate the ciphertext. This specific shift value is referred to as the “key”. The following table is a reference to the decryption process of Caesar cipher:

Alt-image & caption: Caesar Cipher – Index Numbering Value Table

Caesar Cipher Decryption

To perform the Caesar cipher decryption, the following is a step-by-step guide for translating a Caesar Cipher into readable text:

Step-by-Step Guide to Decrypt the Caesar Cipher:

  1. Collect the Ciphertext: Start by obtaining the encrypted message that you want to decrypt. This could be a text, email, or any form of communication that has been encoded using the Caesar cipher.
  2. Choose a Key: To decrypt the message, you need to figure out the shift value that was used during encryption. The standard Caesar cipher uses a shift value of 3. This key signifies how many positions each letter in the plaintext will be shifted backward.
  3. Decrypt the Message: For each letter in the plaintext message, perform the following steps:
    • a. Start with the first letter of the ciphertext and apply the reverse shift to it. For example, if the shift value was 3, and you have the cipher letter “D”, shift it three positions back in the alphabet, resulting in “A”.
    • b. Wrap around the alphabet if necessary. If the shifted position exceeds to “Z”, loop back to the beginning of the alphabet.
    • c. If it’s a special character or number, leave it unchanged.
    • d. Replace the original letter (ciphertext) with the one corresponding to the new position (plaintext).
  4. Repeat for All Letters: Continue this process for every letter in the plaintext message, shifting each one according to the key value.
  5. Collect the Decoded Text: As you complete the decryption for each letter, compile the resulting letters. Once you’ve processed all letters in the ciphertext message, you will have created the plaintext.
  6. Verify the Decryption: After decrypting the entire message, review the text to see if it makes sense. If it’s a valid message in English or the language that you suspect, you’ve successfully decrypted the Caesar cipher.

Example: Let’s decrypt the “NDOL” ciphertext with a Caesar cipher key of 3. Use the following table as a guideline:

Alt-image & caption: Caesar Cipher Decrypt “Kali”

Alt-image & caption: Caesar Cipher Decrypt “Kali”

So, the “NDOL” ciphertext becomes “KALI”.

Mathematical Expression of the Caesar Cipher Decryption

In real applications, the use of the Caesar cipher is not limited to sending the messages in the form of one or two words. Rather, it is a message that usually consists of several paragraphs. So, just imagine if the message consists of 100,000 characters. It would be very tiring if we want to decrypt the message by letter, right?

Therefore, you need to use a program that can automate the decryption process. One of which we will discuss here is decrypting the Caesar cipher using Python.

Before you implement it into a Python program, you have to be able to formulate a form of textual (mathematical) expression so that it can be processed by your program. This is where you need a formula for the Caesar cipher decryption. The following is the Caesar cipher’s decryption mathematical expression:

E(x) = (x- k) mod 26
E(x) Denotes an Encryption of the x alphabetical index
x The index of an alphabet (plaintext)
k The “key” or shift value
mod 26 The modulo operations of the total amount of the alphabet which is 26

We discussed the concept of modulo operation in the article entitled Caesar Cipher Encryption Using Python. If you don’t understand it, it would be a good idea for you to go to the article and come back here for the next material.

Example: Using the given formula, let’s decrypt the “OLQXAKLQW” ciphertext with the shift value of 3.

Alt-image & caption: Caesar Cipher Decryption Using Mathematical Equation

So, the ciphertext of the “OLQXAKLQW” plaintext is “LINUXHINT”.

Implementing the Caesar Cipher Decryption in Python

Now, let’s get practical and see how to implement the Caesar cipher decryption in Python. We’ll walk through the process step by step.

Program Workflow:

  1. You need to have a text file that contains the secret (encrypted) message you want to decode.
  2. Run the program from the command line, telling it which file to use as input. For example, you might say “decrypt secret_message.txt”.
  3. The program takes the encoded (scrambled) text from your file and figures out the original message by reversing the secret code. It does this based on a special number that you specify (it’s 3 by default). This process is called “decryption”.
  4. The program then saves this decoded message in a new file. By default, it’s named “decrypted.txt” but you can give it a different name if you want.

Caesar Cipher Encryption 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. Caesar Cipher Decryption Function

def caesar_cipher_decrypt(text, shift):
    decrypted_text = ""
    for char in text:
        if char.isalpha():
            is_upper = char.isupper()
            char = char.lower()
            decrypted_char = chr(((ord(char) - ord('a') - shift) % 26) + ord('a'))
            if is_upper:
                decrypted_char = decrypted_char.upper()
            decrypted_text += decrypted_char
        else:
            decrypted_text += char
    return decrypted_text

This function takes two arguments: text (the input text to be decrypted) and shift (the shift value for the Caesar cipher).

First, we initialize an empty string which is “decrypted_text” to store the decrypted result later. Then, using the “for” loop, we iterate through each character in the input text with the following conditions:

  • If the character is alphabetical (a letter), it performs the Caesar cipher decryption on it while preserving the case (upper or lower).
  • If the character is not alphabetical (e.g., space, punctuation, etc.), it leaves it unchanged and appends it to the “decrypted_text” string.

Finally, the function returns the decrypted text.

def decrypt_file(input_file, output_file, shift):
    try:
        with open(input_file, 'r') as file:
            ciphertext = file.read()
    except FileNotFoundError:
        print(f"Error: Input file '{input_file}' not found.")
        return

    decrypted_text = caesar_cipher_decrypt(ciphertext, shift)

    try:
        with open(output_file, 'w') as file:
            file.write(decrypted_text)
        print(f"Decryption complete. Decrypted text saved to '{output_file}'.")
    except Exception as e:
        print(f"Error writing to output file: {e}")

3. File Decryption Function

This function takes three arguments: “input_file” (the path to the input file that contains the ciphertext to be decrypted), “output_file” (the path to the output file where the decrypted text will be saved), and “shift” (the shift value for the Caesar cipher).

Inside the function, we attempt to open and read the content of the input file that is specified by “input_file”. If the file is not found, it prints an error message and returns it (by terminating the program). Then, we call the “caesar_cipher_decrypt” function to decrypt the content of the input file with the specified shift. After decryption, it attempts to create and open the output file that is specified by the “output_file” variable for writing. If successful, it writes the decrypted text to the output file and prints a success message.

If there’s any error while writing to the output file, it prints an error message.

4. Main Function

def main():
    parser = argparse.ArgumentParser(description="Decrypt a text file encrypted using Caesar cipher.")
    parser.add_argument("input_file", help="Path to the input file (ciphertext)")
    parser.add_argument("-o", "--output_file", default="decrypted.txt", help="Path to the output file (decrypted) [default: decrypted.txt]")
    parser.add_argument("-s", "--shift", type=int, default=3, help="Shift value for Caesar cipher [default: 3]")
    args = parser.parse_args()

    decrypt_file(args.input_file, args.output_file, args.shift)

The main function is where the program execution starts. It sets up the command-line argument parsing using the “argparse” library.

We define three command-line arguments:

  • input_file (a required argument): This is the path to the input file that contains the ciphertext that you want to decrypt.
  • -o or –output_file (optional argument with a default value of “decrypted.txt”): This allows you to specify the path to the output file where the decrypted text will be saved. If not provided, it defaults to “decrypted.txt”.
  • -s or –shift (optional argument with a default value of 3): This allows you to specify the shift value for the Caesar cipher that is used for decryption. If not provided, it defaults to a shift of 3.

The “argparse” library automatically handles the parsing of the command-line arguments and stores them in the “args” object. It then calls the “decrypt_file” function with the provided input file path, output file path (or the default), and shift value (or the default).

5. Script Execution

if __name__ == "__main__":
    main()

Finally, the script checks if it’s being run as the main program using if “__name__ == “__main__”:” and calls the main function to start the program execution.

That’s it! Here, we save the program to “decrypt_caesar.py”. Run the program with the help argument to show the required options:

python decrypt_caesar.py -h

Our program only requires a path to the file that you want to decrypt. The decrypted text will be saved to a new file, or you can specify a different output file using the -o option. The -s option allows you to specify the Caesar cipher shift value, but it defaults to 3 if not provided.

Proof of Concept

We got an encoded message as shown in the following image. At a glance, we can see this message as a scrambled text:

Fortunately, we know that the encryption method is Caesar cipher and uses 3 as a shift key. So, we run the previous program and do the decryption process. Here is the result:

Try It Yourself

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

Conclusion

Congratulations! You learned how to decrypt the Caesar cipher messages using Python. This tutorial has equipped you with the knowledge and tools to unlock the encrypted secrets. Decrypting the Caesar cipher using Python is a fascinating journey into the world of cryptography. It’s a valuable skill for anyone interested in cybersecurity, code-breaking, or just curious about the secrets of the past. Now, go ahead and try decrypting some secret messages—it’s a fantastic way to exercise your brain and impress your friends with your newfound crypt analysis skills. Happy deciphering!

Frequently Asked Questions (FAQs)

Q1: Can I encrypt the numerical or special characters in Caesar cipher?
A1: The basic Caesar cipher is designed for letters only. Numerical and special characters remain unchanged during encryption.

Q2: Can I use the negative shift values to encrypt the messages?
A2: Yes, you can. Negative shift values will shift the characters to the left in the alphabet, effectively reversing the encryption process.

Q3: Is Python the only language for Caesar cipher decryption?
A3: No, Python is just one of the many programming languages that can be used for Caesar cipher decryption. Other languages like Java, C++, and Ruby can also be employed.

Q4: Is Caesar cipher used in modern cryptography?
A4: Caesar cipher is not used in modern cryptography due to its lack of security. Modern encryption methods rely on complex algorithms and mathematical principles for robust protection.

Share Button

Source: linuxhint.com

Leave a Reply