【发布时间】:2020-11-03 08:20:54
【问题描述】:
我编写了这个原型代码来加密一些文本(反之亦然)。当我将命令设置为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:\Users\xoxo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\cryptography\fernet.py", line 113, in _verify_signature
h.verify(data[-32:])
File "C:\Users\xoxo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\cryptography\hazmat\primitives\hmac.py", line 70, in verify
ctx.verify(signature)
File "C:\Users\xoxo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\cryptography\hazmat\backends\openssl\hmac.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:\Users\xoxo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\cryptography\fernet.py", line 76, in
decrypt
return self._decrypt_data(data, timestamp, ttl, int(time.time()))
File "C:\Users\xoxo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\cryptography\fernet.py", line 125, in _decrypt_data
self._verify_signature(data)
File "C:\Users\xoxo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\cryptography\fernet.py", line 115, in _verify_signature
raise InvalidToken
cryptography.fernet.InvalidToken
【问题讨论】:
-
假设
write方法没有被调用,代码一定会失败。 -
另一个可能的原因是:
EncodingText的每个实例化都会创建一个 new 键。因此,如果您使用一个实例加密(在构造函数中使用self.write())并使用上面的代码使用另一个实例解密,它也应该由于不同的密钥而失败。 -
@Topaco 这是另一个(潜在的)原因。我将把它作为一个完整的答案来演示。
-
如果问题解决了,请采纳答案。
标签: python-3.x cryptography fernet