Vigenère Cipher - Python

200 Views Asked by At

I'm attempting a Vigenere cipher for a class. I'm to use the key word "friends" to unlock the coded message. I can't seem to get the values of the key phrase to add to the values of the coded phrase correctly. I think somehow I'm not iterating through the 'key' properly, but I'm unsure how to trouble shoot.

#following code will attempt to use the key word 'friends', to unlock the coded phrase stored under 'message'.
    message ="dfc aruw fsti gr vjtwhr wznj? vmph otis! cbx swv jipreneo uhllj kpi rahjib eg fjdkwkedhmp!"
    alpha = "abcdefghijklmnopqrstuvwxyz"
    punc = ".!? \/$@^%&*'"
    
    #defining function that will take the coded 'message' and the 'key' phrase, as inputs.
    def decoder(message, key):
        decoded = ""
    #attempting to iterate through the key phrase to obtain it's value, print() here is used to test that the values are seen
        for k in key:
            if k not in punc:
                key_val = alpha.find(k)
                print(key_val)
    #iterating through the 'message' variable to find it's values and exclude the punctuation/spaces.Then, add the 'message'
    #values and 'key' values to get the coded message. 
        for letters in message:
            if letters not in punc:
                message_val = alpha.find(letters)
                decoded += alpha[(message_val + key_val) % 26]
            else:
                decoded += letters
        return decoded
    #output is incorrect.
    decoder(message,"friends")
1

There are 1 best solutions below

4
gogaloh On
for letters in message:
    if letters not in punc:
        message_val = alpha.find(letters)
        key_val=alpha.find(key[counter])
        print(key[counter])
        decoded += alpha[(message_val + key_val) % 26]
        counter+=1
        if counter==7:
            counter=0

    else:
        decoded += letters
return decoded