ASCII Vigenere cipher not decrypting properly

馋奶兔 提交于 2019-12-11 12:35:10

问题


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


来源:https://stackoverflow.com/questions/35711747/ascii-vigenere-cipher-not-decrypting-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!