当我尝试在此行cryptography.fernet.InvalidToken
解密文件的内容时,出现此错误=> exit1 = key.decrypt(listCipher[0])
。
我到处寻找,但没有发现任何有关此问题的信息。我尝试使用ConfigParser替换列表,但它仍然无法正常工作,我不认为这是问题所在。欢迎提供一些帮助。
from cryptography.fernet import Fernet
entry1 = "First_sentence"
entry2 = "Second_sentence"
entry3 = "Third_sentence"
##--- Key creation
firstKey = Fernet.generate_key()
file = open('.\\TEST\\key.key', 'wb')
file.write(firstKey)
file.close()
##--- Cipher entries
key = Fernet(firstKey)
chiffrentry1 = key.encrypt(bytes(entry1, "utf-8"))
chiffrentry2 = key.encrypt(bytes(entry2, "utf-8"))
chiffrentry3 = key.encrypt(bytes(entry3, "utf-8"))
listAll = [chiffrentry1, chiffrentry2, chiffrentry3]
##-- Write cipher text in file
with open('.\\TEST\\text_encrypt.txt', 'w') as pt:
for ligne in listAll:
pt.write("%s\n" % ligne)
##--- Recover file to decrypt cipher text
listCipher = []
with open('.\\TEST\\text_encrypt.txt', 'rb') as pt:
for line in pt:
listCipher.append(line.strip())
exit1 = key.decrypt(listCipher[0])
exit2 = key.decrypt(listCipher[1])
exit3 = key.decrypt(listCipher[2])
print(exit1)
print(exit2)
print(exit3)
最佳答案
'%s\n'%ligne
正在修改您的数据。例如,如果我执行以下操作:
>>> with open('afile.txt', 'w') as fh:
for i in range(2):
fh.write('%s\n'%b'hi there')
12
12
>>> with open('afile.txt', 'rb') as fh:
for line in fh:
print(line)
b"b'hi there'\n"
b"b'hi there'\n"
这里的问题是您正在执行的类型转换。 Fernet的操作需要
bytes
,并且您将加密值存储为string
。当您将bytes
对象转换为string
时,您不会确切地知道该字节字符串是什么。为避免这种情况,请勿转换类型with open('.\\TEST\\text_encrypt.txt', 'wb') as pt:
# join supports byte-strings
to_write = b'\n'.join(listAll)
pt.write(to_write)
# Now I can read a bytes object directly
with open('.\\TEST\\text_encrypt.txt', 'rb') as fh:
# this is a single bytes-string with b'\n' chars inside it
contents = fh.read()
# byte-strings also support split
ciphers = contents.split(b'\n')
for cipher in ciphers:
print(key.decrypt(cipher))
关于python - 带有python加密模块的InvalidToken,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54874767/