您需要使用与加密数据相同的密钥在这里您正在生成一个新密钥并尝试使用它来解密您之前使用不同密钥加密的数据。在下面的代码示例中。你可以看到我已经生成了 2 个密钥。我用第一个密钥加密数据,我可以用第一个密钥成功解密它。但是,如果我尝试使用第二个密钥解密,则会收到无效令牌错误,因为这不是我用来加密数据的密钥
from cryptography.fernet import Fernet
def my_encrypt(key, data):
f = Fernet(key)
return f.encrypt(data)
def my_decrypt(key, data):
f = Fernet(key)
return f.decrypt(data)
my_key = Fernet.generate_key()
other_key = Fernet.generate_key()
my_string = b"my deep dark secret"
print(my_string)
my_encrypt_string = my_encrypt(my_key, my_string)
print(my_encrypt_string)
my_decrypt_string = my_decrypt(my_key, my_encrypt_string)
print(my_decrypt_string)
other_decrypt_string = my_decrypt(other_key, my_encrypt_string)
输出
b'my deep dark secret'
b'gAAAAABdSoKHUm4xCGDZ1JYneogK62U_GQnluw-ekn8xRi0rT8_9FzK0iMY41pksCg5OpPgoD0pJlJFsGF4WjIMeMWVpPdkQklL2JjQbbEhfcx6Qpazm_eA='
b'my deep dark secret'
Traceback (most recent call last):
File "C:\Users\cd00119621\AppData\Local\Programs\Python\Python37\lib\site-packages\cryptography\fernet.py", line 106, in _verify_signature
h.verify(data[-32:])
File "C:\Users\cd00119621\AppData\Local\Programs\Python\Python37\lib\site-packages\cryptography\hazmat\primitives\hmac.py", line 69, in verify
ctx.verify(signature)
File "C:\Users\cd00119621\AppData\Local\Programs\Python\Python37\lib\site-packages\cryptography\hazmat\backends\openssl\hmac.py", line 73, 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/cd00119621/PycharmProjects/ideas/stackoverflow.py", line 22, in <module>
other_decrypt_string = my_decrypt(other_key, my_encrypt_string)
File "C:/Users/cd00119621/PycharmProjects/ideas/stackoverflow.py", line 11, in my_decrypt
return f.decrypt(data)
File "C:\Users\cd00119621\AppData\Local\Programs\Python\Python37\lib\site-packages\cryptography\fernet.py", line 75, in decrypt
return self._decrypt_data(data, timestamp, ttl)
File "C:\Users\cd00119621\AppData\Local\Programs\Python\Python37\lib\site-packages\cryptography\fernet.py", line 119, in _decrypt_data
self._verify_signature(data)
File "C:\Users\cd00119621\AppData\Local\Programs\Python\Python37\lib\site-packages\cryptography\fernet.py", line 108, in _verify_signature
raise InvalidToken
cryptography.fernet.InvalidToken
因此,当您加密数据时,您需要存储用于加密它的密钥,因为您将需要使用相同的密钥来解密它