我编写了一个python vigenere密码,它不接受空格,所以我添加了一些代码,现在它不会打印正确的输出。
如果输入为'计算很有趣'且关键字为'gcse',则输出应为'jrfubwbsn ll kbq'。在我的程序中,输出是'jrfubwbsn bx ins'。
以下是vigenere cipher的工作原理。
代码如下:
from itertools import cycle
print("NOTE: The program does not encrpyt/decrypt numbers or ASCII characters. These include punctuation marks. Trying to encrypt/decrypt these values will print an error and you will have to try again.\n")
def main():
def encrypt():
boolean = False
while boolean == False:
message = str(input("Input a message: "))
keyword = input("Keyword: ")
if message.isdigit() == True or keyword.isdigit() == True:
print("Invalid data type! Please try again.\n")
else:
boolean = True
keystream = cycle(keyword)
encrypted_msg = ''
for msg, key in zip(message, keystream):
spaceChar = 0
newMsg = ord(msg)
newKey = ord(key)
switch = True
if newMsg == 32:
encrypted_msg += " "
switch = False
else:
pass
if switch == True:
if 64 < newMsg < 91:
newMsg -= 64
elif 96 < newMsg < 123:
newMsg -= 96
else:
pass
if 64 < newKey < 91:
newKey -= 64
elif 96 < newKey < 123:
newKey -= 96
else:
pass
newChar = newMsg + newKey + 96
if newChar > 122:
newChar = newChar - 26
elif 96 > newChar > 91:
newChar -= 26
encrypted_msg += chr(newChar)
else:
pass
print("Encrypted message: %s" %encrypted_msg)
def decrypt():
boolean = False
while boolean == False:
message = str(input("Input a message: "))
keyword = input("Keyword: ")
if message.isalpha() == True or keyword.isalpha() == True:
boolean = True
elif message.isalpha() == False:
print("Invalid data type! Please try again.\n")
else:
pass
keystream = cycle(keyword)
decrypted_msg = ''
for msg, key in zip(message, keystream):
newMsg = ord(msg)
newKey = ord(key)
if 64 < newMsg < 91:
newMsg -= 64
elif 96 < newMsg < 123:
newMsg -= 96
else:
pass
if 64 < newKey < 91:
newKey -= 64
elif 96 < newKey < 123:
newKey -= 96
else:
pass
newMsg = ord(msg) - 96
newKey = ord(key) - 96
newChar = newMsg - newKey + 96
if newChar > 122:
newChar = newChar - 26
elif 96 > newChar > 91:
newChar -= 26
decrypted_msg += chr(newChar)
print("Decrypted message: %s" %decrypted_msg)
def task2choice():
boolean = False
while boolean == False:
choice = str(input("Encrypt or Decrypt. [e/d]: "))
print(" ")
if choice.lower() == 'e' or choice.lower() == 'd':
boolean = True
else:
print("Please select 'e' or 'd'.")
if choice.lower() == 'e':
encrypt()
elif choice.lower() == 'd':
decrypt()
else:
pass
print(' ')
task2choice()
def again():
again = input("Would you like to restart? [y/n]: ")
return again.lower() == 'y'
while main() or again():
pass
出现问题是因为for循环检查空格并跳过关键字中的字母。 任何帮助将不胜感激。提前谢谢。