[英]Vigenere Cypher in Python
我正在尝试用Python编写vigenere应用程序。 这是应用程序应运行的方式:
密文密钥是一串字母数字chars
,然后将其转换为int
,该数字用于将纯文本旋转为密文。 例如: A
或a
旋转一个字母进行加密解密的权利或一个字母的左边。
几乎一切正常。 如果我输入英语纯文本文件,对其进行加密,然后使用相同的密钥对该文件解密,则输出文件应该与我开始使用的纯文本文件完全一样...并且除了换行符外。 一些原有的换行符已消失,而一些新的换行符也已投入使用。
我花了很长时间试图了解自己在做什么错。 我将不胜感激。 这是完整的代码:
# ask user if he/she wishes to encrypt or decrypt a message
pmode = 0
while True:
try:
pmode = int(input("Enter 1 to encrypt or 2 to decrypt a message: "))
while pmode not in {1, 2}:
int(input("Oops! Please enter 1 or 2: "))
break
break
except (ValueError, NameError):
print("Oops! That entry is not supported, try again...")
# ask user for a cypher keyword
key = input("Enter codeword: ")
# create list to store converted key
keylength = len(key)
realkey = [] * keylength
# convert "key" from string of chars to string of ints
for i in key:
if i.isalpha():
if i.isupper():
realkey.append(ord(i) % ord('A') + 1)
elif i.islower():
realkey.append(ord(i) % ord('a') + 1)
elif ord(i) >= 48 and ord(i) <=57:
realkey.append(int(i))
else:
realkey.append(0)
# prompt user for input file and open it
infile_name = input("Enter input file name: ")
infile = open(infile_name, 'r')
# prompt user for output file and open it
outfiler_name = input("Enter output file name: ")
outfile = open(outfiler_name, "w")
# if on encryption mode, encrypt
if pmode == 1:
# iterate over inmessage and rotate (within ASCII chars 32 - 126) using realkey
indx = -1
# loop over infile, encrypt and write to outfile
while True:
# temp variable to store current char
char = infile.read(1)
indx += 1
# stop when EOF is reached
if not char:
break
else:
if ord(char) + realkey[indx % keylength] > 126:
outfile.write(chr((ord(char) - 126 + realkey[indx % keylength])))
else:
outfile.write(chr((ord(char) + realkey[indx % keylength])))
else:
# iterate over inmessage and rotate (within ASCII chars 32 - 126) using realkey
indx = -1
# loop over infile, encrypt and write to outfile
while True:
# temp variable to store current char
char = infile.read(1)
indx += 1
# stop when EOF is reached
if not char:
break
else:
if ord(char) + realkey[indx % keylength] < 32:
outfile.write(chr((ord(char) + 126 - realkey[indx % keylength])))
else:
outfile.write(chr((ord(char) - realkey[indx % keylength])))
# close files
infile.close()
outfile.close()
谢谢。
因为\\n
(换行符)是ascii 10,所以请记住ord('\\ n')== 10
此时您有2种可能性
ord(char) + realkey[indx % keylength] < 32:
ord(key_letter)-ord('a') >= 22
1
),则10 + 126 + 1 = 137(或'\\x89'
) ord(char) + realkey[indx % keylength] < 32:
的if语句为false 89 - 1
,这肯定不会使我们回到10,因此这将字符串解码为错误 我想答案是您的算法在很多情况下都会崩溃...并且应该完全重构....我将为您提供一些重构的建议,这将有助于使其更易于测试
key="Yellow55"
my_string="Hello\\nTest\\t\\rString\\r\\n"
...真的,只使用string.printable
作为应该包括所有ascii字母作为测试用例... def decrypt(string_to_decrypt,key):
#do your stuff
def encrypt(string_to_encrypt,key):
#do your stuff
而不是while True: i+=1 ...
您应该将for i,value in enumerate(my_list):
如果您无法出于某种原因打印所有内容,请至少使用调试器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.