How would I fix my Vigenere Cipher Decryption

86 views Asked by At

I'm having an issue with Vigenere Cipher Decryption, When an encrypted message is decrypted, the decrypted message is not printed, but the encrypted is?

I cant seem to see why this dose not work. But its probably a simple issue. I think the issue is in the main decrypt function. Help would be much appreciated

Encryption works fine

def encrypt_key(message, key):    
    i = 0
    empty_key = '' # empty key to append to 

    # turn characters into index
    for characters in message:
        if characters.isalpha(): # checks if character is in the alphabet
            empty_key = empty_key + key[i % len(key)] # append characters to empty key
            i = i + 1 # increase integer value by 1
        else: 
            empty_key = empty_key + ' ' # if character is a space or punctuation then add empty space
    return empty_key

def encrypt_decrypt(message_char, key_char, choice='encrypt'):
    if message_char.isalpha():
        first_alphabet_letter = 'a' # assume character is lowercase
        if message_char.isupper():
            first_alphabet_letter = 'A' # assume character is upper, then replace with A

        original_char_position = ord(message_char) - ord(first_alphabet_letter) # difference results in position of char in alphabet
        key_char_position = ord(key_char.lower()) - ord('a')

        if choice == 'encrypt':
            new_char_position = (original_char_position + key_char_position) % 26 # encrypts & loops back around with % 26
        
        else: # if choice == 'decrypt':

            new_char_position = (original_char_position - key_char_position + 26) % 26 # decrypts & loops back around
        return chr(new_char_position + ord(first_alphabet_letter))
    return message_char

def encrypt(message, key):
    cipher = ''
    empty_key = encrypt_key(message, key)

    for message_char, key_char in zip(message, empty_key):
        cipher = cipher + encrypt_decrypt(message_char, key_char)
    return cipher

def decrypt(cipher, key):
    message = ''
    empty_key = encrypt_key(cipher, key)

    for cipher_char, key_char in zip(cipher, empty_key):
        message = message + encrypt_decrypt(cipher_char, key_char, 'decrypt')
    return message

message = input('Enter your message to encrypt here: ')
key = input('Enter your key: ')

cipher = encrypt(message, key) # inputs message and key to encrypt function
decrypt_message = decrypt(cipher, key)# inputs message and key to decrypt function


print(f'Cipher: {cipher}')
print(f'Decrypted: {decrypt_message}')

def choice():
    user_choice = int(input('''
Enter your choice (1 or 2):

1. Encrypt
2. Decrypt

>  '''))
    if user_choice == 1:
        print(f'Cipher: {cipher}')
        print('')
    elif user_choice == 2:
        print('')
        print(f'Decrypted: {decrypt_message}')

choice()
0

There are 0 answers