| by Arround The Web | No comments

Decrypting Vigenère Cipher Mathematical Equation and Python Tutorial

Topic of Contents:

  1. Introduction to Vigenère Cipher Decryption
  2. Vigenère Cipher Decryption Mathematical Equation
  3. Vigenère Cipher Decryption Python Expression
  4. Proof of Concept – Decryption Execution
  5. Conclusion
  6. Frequently Asked Questions (FAQs)

Introduction to Vigenère Cipher Decryption

The Vigenère cipher is an encryption technique that involves altering each letter of the plaintext based on a keyword using a simple polyalphabetic substitution method. It shifts the position of each letter in the alphabet according to the provided key.

After we learn the encryption using the Vigenère cipher in the previous article, we then should be able to understand how the decryption process works. Trust me, it’s very easy. Remember that you already understand the fundamentals of Vigenère cipher such as tabula recta and modulo operation.

Vigenère Cipher Decryption Mathematical Equation

The mathematical equation for the Vigenère cipher Decryption is:

Dx = (Ex – Kx) mod 26
Dx Denotes the x index of the Decrypted (plain) letter
Ex The x index of an Encrypted (cipher) letter
Kx The Key index
mod 26 The modulo operations of the total amount of the alphabet which is 26

Please remember that index numbering starts with 0 to represent the alphabet in numeric (0-25).


Alt-image & caption: Index Numbering Value

For example, we have given the “DMPLBAARV” ciphertext with the “SECRET” key.


Alt-image & caption: Vigenère Cipher Decryption

To decode this Vigenère cipher using the previous equation, we first need to identify each cipher letter and the key index numbers. For the first cipher letter “D”, the index is 3 and the key “S” has an index of 18.


Alt-image & caption: Vigenère Cipher Decryption

Using the equation, we then calculate each pair of plain and key index numbers to produce the plain letter index (Dx) since the first cipher letter “D” and the key “S” generates an equation as follows:

Dx = (3 - 18) mod 26
Dx = -15 mod 26
Dx = 11
D  = L

Calculate until the last cipher letter. The result is shown in the following:


Alt-image & caption: Vigenère Cipher Decryption

So, the “DMPLBAARV” ciphertext with the “SECRET” key is decrypted to “LINUXHINT”.

Vigenère Cipher Decryption Python Expression

What if you receive a very long encrypted message with the known key? It will be time-consuming if you calculate manually per letter using the previous equation, right? To solve this problem, you need a program to automate the decode process. Here is the step-by-step explanation on how to build a Python program to decrypt the Vigenère ciphertext.

1. Import the Required Library
We need the “argparse” module to handle the command-line arguments and the “os” module for the file path manipulation later.

import argparse
import os

2. Define the Vigenère Cipher Decryption Function

Then, we define the Vigenère decryption function called “decrypt_vigenere”. This function takes the encrypted text and key as inputs. Then, the Vigenère cipher decrypts the encrypted text using the provided key while preserving the non-alphabetic characters. The decryption process ensures that the position of characters is maintained accurately in the decrypted text.

def decrypt_vigenere(encrypted_text, key):
    decrypted_text = ""
    key_length = len(key)
    key_index = 0
    for char in encrypted_text:
        if char.isalpha():
            key_shift = ord(key[key_index % key_length].upper()) - 65
            if char.isupper():
                decrypted_text += chr((ord(char) - 65 - key_shift) % 26 + 65)
            else:
                decrypted_text += chr((ord(char) - 97 - key_shift) % 26 + 97)
            key_index += 1
        else:
            decrypted_text += char
    return decrypted_text

3. The Conditional Main Function

Then, we define a conditional main function. Using the “argparse” module, the script sets up a command-line interface to handle the arguments. It expects the input file path and allows for optional specification of the output file path and the decryption key. If the output file path is not provided, the script generates a default output file name based on the input file name.

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Vigenère Cipher Decryption of a Text File')
    parser.add_argument('input_file', help='Path to the input file')
    parser.add_argument('--output_file', help='Path to the output file', default="")
    parser.add_argument('--key', help='Decryption key', default='secret')

    args = parser.parse_args()

    if not args.output_file:
        input_file_name, _ = os.path.splitext(args.input_file)
        args.output_file = f"decrypted_{os.path.basename(input_file_name)}.txt"

    try:
        with open(args.input_file, 'r') as file:
            encrypted_text = file.read()
            decrypted_text = decrypt_vigenere(encrypted_text, args.key)

            with open(args.output_file, 'w') as output_file:
                output_file.write(decrypted_text)

            print(f"Decryption successful. Decrypted text written to {args.output_file}")
    except FileNotFoundError:
        print("Input file not found. Please check the file path.")
    except Exception as e:
        print(f"An error occurred: {e}")

The script utilizes the exception handling to catch the potential errors during file operations and decryption. If the input file is not found, the script provides a helpful error message. Additionally, any other unexpected errors during the decryption process are caught, and the script displays a detailed error information to assist with troubleshooting.

The main script execution involves reading the input file, decrypting the Vigenère cipher text using the provided key, and writing the decrypted text to the specified output file. The script concludes by printing a success message, confirming the completion of the decryption process and providing the path to the decrypted output file.

Finally, our program is complete. Save it to “decrypt_vigenere.py”. Now, for the first run, type the following command:

Python decrypt_vigenere.py -h

Proof of Concept

It’s time to execute the program. Now, we received an encrypted text. Fortunately, we know that the key is “SUPERSECRET” and it is encoded using the Vigenère cipher. The ciphertext is as shown in the following:


Alt-image & caption: Vigenère Ciphertext

It’s hard to read, right? We then fire up our Python Vigenère decoder program and type in the following command:

python decrypt_vigenere.py --key SUPERSECRET encrypted_message.txt


Alt-image & caption: Proof of Concept Vigenère Cipher Decryption Python Program

Try It Yourself

Download this program source code on our GitHub page at https://github.com/bimando/Vigenere-Cipher and try it yourself.

Conclusion

To sum up, the Vigenère cipher is a nifty way to keep the messages secret by scrambling the letters using a keyword. We’ve seen how to encrypt and decrypt the messages using this method. Decrypting the messages involves reversing the process that we used for encryption. Understanding the basics of the Vigenère cipher, like the special table (tabula recta) and the modulo operation, helps us make sense of the decryption steps.

The decryption formula, Dx = (Ex – Kx) mod 26, is the key to understanding how to decode the encrypted message. We can use this formula to decode each letter of the encrypted text. Moreover, we can simplify the decoding process using a Python program, “decrypt_vigenere.py”, which automates the decryption for us. This program helps us to quickly unravel the long, encrypted messages without getting tangled up in the math.

Frequently Asked Questions (FAQs)

Q1: What role does the Vigenère cipher decryption mathematical equation play?
A1: The equation is crucial for reversing the encryption process, enabling the restoration of the original plaintext from the ciphertext.

Q2: How does the Vigenère cipher decryption Python program simplify the decryption process?
A2: The program automates the decoding of encrypted messages, saving time and effort that would otherwise be required for manual decryption.

Q3: How does Vigenère cipher decryption differ from encryption?
A3: Decryption involves the reversal of the encryption process, utilizing the decryption mathematical equation to decipher the encrypted message accurately.

Share Button

Source: linuxhint.com

Leave a Reply