Vigenere Cipher Python

41 Views Asked by At

My code is supposed to iterate through several documents, apply the Vigenere cipher, and return the decrypted and encrypted messages. I know that within the files exists a decrypted message. However, despite me having the correct key, it still doesn't return the correct output. I genuinely don't understand what's wrong with my code. I'm a bit new to programming, but, after much troubleshooting, I can't solve this.

import os

alphabet = "".join(chr(i) for i in range(32, 127))
key = "cumberbatch"

letter_to_index = dict(zip(alphabet, range(len(alphabet))))
index_to_letter = dict(zip(range(len(alphabet)), alphabet))


def encrypt(message, key):
    encrypted = ""
    split_message = [
        message[i: i + len(key)] for i in range(0, len(message), len(key))
    ]

    for each_split in split_message:
        i = 0
        for letter in each_split:
            number = (letter_to_index[letter] + letter_to_index[key[i]]) % len(alphabet)
            encrypted += index_to_letter[number]
            i += 1

    return encrypted


def decrypt(cipher, key):
    decrypted = ""
    split_encrypted = [
        cipher[i: i + len(key)] for i in range(0, len(cipher), len(key))
    ]

    for each_split in split_encrypted:
        i = 0
        for letter in each_split:
            number = (letter_to_index[letter] - letter_to_index[key[i]]) % len(alphabet)
            decrypted += index_to_letter[number]
            i += 1

    return decrypted


def process_file(file_path):
    with open(file_path, 'r') as file:
        content = file.read()
        encrypted_content = encrypt(content, key)
        decrypted_content = decrypt(encrypted_content, key)

        print(f"File: {file_path}")
        print("Original content:\n", content)
        print("\nEncrypted content:\n", encrypted_content)
        print("\nDecrypted content:\n", decrypted_content)
        print("\n" + "=" * 40 + "\n")


def main():
    folder_path = "Detected_Files"

    for filename in os.listdir(folder_path):
        if filename.endswith(".txt"):
            file_path = os.path.join(folder_path, filename)
            process_file(file_path)


if __name__ == "__main__":
    main()

I have three documents in the folder "Detected_Files". In this folder, I know with 99% certainty that there's a message containing a Vigenère cipher. However, when I ran the code, the text was not deciphered properly. This code is being run on Idle python btw.

0

There are 0 best solutions below