我似乎无法使用加密中使用的密钥来
decrypt
行。并且总是收到“无效令牌”解密错误'
我希望使用该程序添加密码,对其进行加密,然后写入文件。如果您打开文件,您将看到的只是加密文本,并且只能使用程序本身查看您的密码。
这是我的代码:
from cryptography.fernet import Fernet
key = b'Sw42CeEyZCyRyct0Ly2loEga9D4iv6tF0WRiTLKVdDA='
fkey = Fernet(key)
def add():
app = input("enter app name ").upper()
name = input("enter account name ")
password = input("enter account password ")
with open("passwords2.txt", 'a') as f:
original = "{}: {} | {} ".format(app, name, password)
inbytes = original.encode()
originalencrypted = fkey.encrypt(inbytes)
f.write(str(originalencrypted) + "\n")
def read():
with open("passwords2.txt", 'r') as f:
for line in f:
print(fkey.decrypt(line.strip().encode()).decode())
while True:
operation = input("would you like to read, add, or quit (q) ")
if operation == "read":
read()
elif operation == "add":
add()
elif operation == "q" or operation == "quit":
quit()
else:
print("invalid input")
问题是
str(originalencrypted)
(它创建像这样的字符串"b'...'"
,而不是使用某种定义的编码将bytes
转换为str
)。
您想要将
bytes
正确转换为 str
:originalencrypted.decode('utf-8')
。
或者你想直接向文件写入字节:
with open("passwords2.txt", 'ab') as f:
...
f.write(originalencrypted)
f.write("\n".encode('utf-8'))