我还是个初学者,我正在使用加密模块在 python 中制作一个简单的密码管理器。用户可以输入程序名称和密码,并将其加密然后写入文件。他们还可以查看添加到文件中的密码。当用户选择此选项时,他们输入要查找的程序/服务的名称,然后通过逐行解密文件并检查程序名称是否在该文件中来返回匹配的密码。我希望这是有道理的。
我遇到的问题是,当程序在选择“查看”并输入名称后尝试解密文件中的行时,即使文件不为空,我也会得到
raise InvalidToken cryptography.fernet.InvalidToken
。我真的不确定为什么,因为密钥不是在程序中生成的,而是存储在文件中,因此每次程序运行时都会读取相同的密钥。我已经以字节为单位读取文件,而不是字符串。我还有另一个更简单的程序,它使用相同的文件,并且可以成功地对文件进行加密和解密,所以我感觉我在其他地方犯了错误。
这是我的程序(错误发生在第58行):
from cryptography.fernet import Fernet
#Get key from file
filekey = open("filekey.key", "rb")
key = filekey.read()
fernet = Fernet(key)
filekey.close()
cmd = "" #Force entry to loop
#Run until user quits
while cmd != "quit":
cmd = input("[add | view | quit] ")
#Input validation loop
while cmd not in ["add", "view", "quit"]:
print("Not a valid command. Try again.")
cmd = input("[add | view | quit]")
#Run if user enters "add"
if cmd == "add":
#Get user input for name and password
name = input("Enter name: ")
pwd = input("Enter password: ")
#Concatenate and encode input
new_line = name + " " + pwd
byte_new_line = new_line.encode()
#Encrypt and convert to string
enc_line = fernet.encrypt(byte_new_line)
enc_line_str = str(enc_line)
#Write string to file
outfile = open("passwords.data", "a")
outfile.write(enc_line_str)
outfile.close()
#Run if user enters "view"
if cmd == "view":
found = False #Keep track of whether name is present in file
#Get user input for name to find
search = input("Name to search for: ")
#Open file to search from
infile = open("passwords.data", "rb")
line = infile.readline()
#Read each line of file
while line != "":
line = infile.readline()
#Decrypt line and convert to string
line_dec = fernet.decrypt(line) #Error here
line_dec_str = str(line_dec)
#Get index of name in decoded string
index = line_dec_str.find(search)
#Run if name is found in string
if index != -1:
#Change found to True and print string
found = True
print(line_dec_str)
#Display error if name not found
if found == False:
print("Error: name not found in file. Try again.")
infile.close()
任何帮助将不胜感激☺️
我刚刚修好了!经过进一步测试,我发现编码发生了一些奇怪的事情。深入挖掘后,我注意到从文件中读取加密字节后,它们看起来像这样:
b"b'加密文本'"
我不知道为什么这样做,但我只是删除了额外的 b 和一组带有切片的引号,因此它具有正确的字节格式:
b'加密文本'
通过查看代码永远不会猜到这是问题所在。但现在已经解决了,所以我希望这个答案可以帮助别人。