我正在尝试一个涉及使用 Fernet 库加密密码的项目。我已经能够输入、加密和存储密码,但当我尝试检索和解密密码时,我不断收到以下错误。
Traceback (most recent call last):<br/>
File "D:\Documents\python\practiceProjects\05 passwordManager\passwordManageV2.py", line 104, in <module>
pm.view()<br/>
File "D:\Documents\python\practiceProjects\05 passwordManager\passwordManageV2.py", line 82, in view
print (f'\nUser: {user}, Password: {Fernet(self.key).decrypt(passw).decode()}\n')<br/>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br/>
File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\cryptography\fernet.py", line 84, in decrypt
timestamp, data = Fernet._get_unverified_token_data(token)<br/>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br/>
File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\cryptography\fernet.py", line 118, in _get_unverified_token_data
raise InvalidToken<br/>
cryptography.fernet.InvalidToken<br/>
为了解密数据,我一直使用代码:
Fernet(self.key).decrypt(passw).decode()
self.key 的形式为 b'key',而唯一的密钥(减去 b' ')存储在 key.key 文件中。此外,当我查看密码文件时,我可以看到密码在写入文件之前已被加密
Site:b'gAAAAABl9KjKHh4MaltYyguafWmjwNjd35wbvfyMZMZEu-t3pabud_B7TDRIjVBaAWKkeZURYN0IGDsKD2XKkdtN2yycFrBlrw=='
任何帮助将不胜感激。
我想知道您是否无法以二进制模式读取/写入文件?这是一个工作示例。
写入密钥和加密数据:
from cryptography.fernet import Fernet
data = "my deep dark secret"
key = Fernet.generate_key()
f = Fernet(key)
token = f.encrypt(data.encode())
with open("example.key", "wb") as fd:
fd.write(key)
with open("example.data", "wb") as fd:
fd.write(token)
读取密钥并解密数据:
from cryptography.fernet import Fernet
with open("example.key", "rb") as fd:
key = fd.read()
f = Fernet(key)
with open("example.data", "rb") as fd:
token = fd.read()
data = f.decrypt(token)
print(data.decode())
请注意,此代码负责将原始字符串编码为其 utf-8 表示形式,然后在解密数据时将其解码回 Python 字符串。