我编写这个原型代码是为了加密一些文本(反之亦然(。当我将命令设置为self.get()
而self.write
正常工作时,我一直会收到这个错误。我不知道是什么原因导致了这个错误或如何解决它…帮助…
from cryptography.fernet import Fernet
class EncodingText:
def __init__(self):
self.key = Fernet.generate_key()
self.f = Fernet(self.key)
self.get()
def write(self):
stuff = "hello there".encode()
token = self.f.encrypt(stuff)
open_file_for_edit = open("file.txt", 'wb')
open_file_for_edit.write(token)
open_file_for_edit.close()
def get(self):
read_file = open("file.txt", 'rb')
reading = read_file.read()
print(reading)
token = self.f.decrypt(reading)
print(token)
read_file.close()
if __name__ == "__main__":
EncodingText()
我得到的错误如下:
Traceback (most recent call last):
File "C:UsersxoxoAppDataLocalProgramsPythonPython38-32libsite-packagescryptographyfernet.py", line 113, in _verify_signature
h.verify(data[-32:])
File "C:UsersxoxoAppDataLocalProgramsPythonPython38-32libsite-packagescryptographyhazmatprimitiveshmac.py", line 70, in verify
ctx.verify(signature)
File "C:UsersxoxoAppDataLocalProgramsPythonPython38-32libsite-packagescryptographyhazmatbackendsopensslhmac.py", line 78, in verify
raise InvalidSignature("Signature did not match digest.")
cryptography.exceptions.InvalidSignature: Signature did not match digest.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:/Users/xoxo/Desktop/Python Programs/xoxo/xoxo.py", line 26, in <module>
EncodingText()
File "c:/Users/xoxo/Desktop/Python Programs/xoxo/xoxo.py", line 7, in __init__
self.get()
File "c:/Users/xoxo/Desktop/Python Programs/xoxo/xoxo.py", line 20, in get
tokenf = self.f.decrypt(reading)
File "C:UsersxoxoAppDataLocalProgramsPythonPython38-32libsite-packagescryptographyfernet.py", line 76, in
decrypt
return self._decrypt_data(data, timestamp, ttl, int(time.time()))
File "C:UsersxoxoAppDataLocalProgramsPythonPython38-32libsite-packagescryptographyfernet.py", line 125, in _decrypt_data
self._verify_signature(data)
File "C:UsersxoxoAppDataLocalProgramsPythonPython38-32libsite-packagescryptographyfernet.py", line 115, in _verify_signature
raise InvalidToken
cryptography.fernet.InvalidToken
让我们逐行浏览代码:
-
在方法
__init__
:中-
第1行:密钥生成。
self.key = Fernet.generate_key() # this is called
每次调用该方法时,我们都会生成一个随机密钥。
-
第2行:密码生成
self.f = Fernet(self.key)
我们正在创建一个带有完全随机密钥的密码。
-
第3行:解密
self.get()
我们正在调用一个新方法。
-
-
方法
get
:-
第1、2和3行:读取文件
read_file = open("file.txt", 'rb') reading = read_file.read() print(reading)
在这里,有两件事是可能的。
路径中缺少文件,并且
FileNotFoundError
被引发,程序停止。文件已存在。
假设文件存在(#2(。将读取文件内容并打印内容。
-
第4行:解密
token = self.f.decrypt(reading)
在这里,我们的文件内容将被解密。请记住,从第1.1.1点开始1.1.2,每次调用我们的程序时,都会生成一个随机密钥和密码是用随机密钥生成的。
由于
Fernet
在实现时使用了对称密码AES
,因此我们需要相同的密钥用于加密和解密。但是,到1.1.1和1.1.2时,我们每次程序都会生成一个随机密钥跑步。
这解释了错误消息。密码正在尝试解密来自用一个完全随机的密钥和另一个随机密钥加密的文件密钥,导致不正确的解密。
-
如果在self.get()
之前插入self.write()
,程序将运行。这是因为使用相同的密钥来解密数据。