-->

ASCII Vigenere cipher not decrypting properly

2019-08-09 07:00发布

问题:

My Vigenere cipher program has all come down to two lists. One a list of ASCII numbers which represent the characters of the message to be encrypted/decrypted and the other is a list of ASCII numbers of the key that would be used to decrypt/encrypt the message.

For encryption:

encryption = [((x + y) % 26) + ord('A') if x < 128 else x for x, y in zip(msglist, keylist)]

for decryption:

encryption = [((x - y) % 26) + ord('A') if x < 128 else x for x, y in zip(msglist, keylist)]

If I input 'Python' with the key 'love' to encrypt I get:

GYAXLN

Unfortunately, when I try to decrypt 'GYAXLN' using the same key I get:

PEZNUT

Which is not what it should be. I think there is something wrong with my math but I just can't quite get it right and up till now have been trying different numbers to see what works (I'm not the best at maths). What am I missing here? Can it not all be done in a list comprehension?

回答1:

The problem is in the statement (x - y) % 26 because mod of a number is defined from 0 to m-1, in the above case 0 to 25, but while subtracting you get negative numbers, so in order to get the correct result you should do this (x - y + 26) % 26. If the negative value we get by (x-y) is lower than "-m" in the above case lower than -26, then the no still remains negative, then you have to make it positive, here is the pseudo code for that :

val = (x - y) % 26
while(val < 0) val += 26
val = val % 26