【发布时间】:2015-11-18 15:33:43
【问题描述】:
我一直在编写 Vigenere Cipher,但程序在到达第 26 个字母 z 之前会循环返回。如果值为 122,而不是打印 z,甚至可能是 a,它会打印第 96 个 ASCII 字符 - `。
这是我的代码:
def getMode():
while True:
mode = input("enter encrypt, e, decrypt or d: ")
if mode in 'encrypt e decrypt d ENCRYPT E DECRYPT D Encrypt Decrypt'.split():
return mode
else:
input('Please enter encrypt or decrypt to start: ')
mode = getMode()
message = input('Enter your message: ')
for char in ' ?.,:;-!/':
message = message.replace(char,'')
key = input('Enter the one word key: ')
times = len(message)//len(key)+1
encryptedKey = (times*key)[:len(message)]
output = []
for character in message:
number = ord(character) - 96
output.append(number)
outputKey = []
for character in encryptedKey:
numberKey = ord(character) - 96
outputKey.append(numberKey)
if mode[0] == 'd':
outputKey = [-x for x in outputKey]
encryptedMessage = [(outputKey[i] + output[i])%26 for i in range(len(output))]
finalMessage = ''.join(chr(c + 96) for c in encryptedMessage)
print(message)
print(encryptedKey)
print(outputKey)
print(output)
print(encryptedMessage)
print('Your encrypted message is: ' + finalMessage)
基本上,如果我输入这个:
enter encrypt, e, decrypt or d: e
Enter your message: abcdefghijklmnopqrstuvwxyz
Enter the one word key: yo
abcdefghijklmnopqrstuvwxyz
yoyoyoyoyoyoyoyoyoyoyoyoyo
[25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15, 25, 15]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
[0, 17, 2, 19, 4, 21, 6, 23, 8, 25, 10, 1, 12, 3, 14, 5, 16, 7, 18, 9, 20, 11, 22, 13, 24, 15]
Your encrypted message is: `qbsdufwhyjalcnepgritkvmxo
应该是 z 的数字,26,现在是 `,我不知道我做了什么让这个循环提前循环。
这是一个小问题,但确实会搞砸消息。任何帮助表示赞赏 - 如果已经有这样的问题(虽然我找不到)请重定向我!
谢谢!
【问题讨论】:
-
“对不起,我真的不知道如何让文本看起来像代码块”——缩进四个字符或更多。
标签: python encryption ascii vigenere