我对Python和加密模块cryptography比较新,所以我正在学习加密和解密的基础知识。 当我在同一个程序中加密文件并进行解密时,一切都运作正常,但如果我尝试仅对一个预先加密的文件运行解密代码(当然我使用了相同的密钥),我会得到InvalidSignature错误,随后是InvalidToken。
现在,我认为由于某种原因密钥不匹配,但它们确实是相同的。 然后我想,也许我将字符串传递给函数而不是字节,或者可能存在某些转换错误可能会改变加密的消息。但加密-解密代码可以工作,所以我无法找出为什么仅解密应该遇到错误。 最后,我查看了解密函数的源代码,并尝试弄清楚时间戳是否与我收到的错误有关,但由于经验不够,我无法获得相关信息。 这是加密-解密代码:程序通过用户提供密码来加密并打印一个文件,可立即进行解密。
import base64
import os
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
print("Insert password: ")
password_str = input()
password = password_str.encode()
salt = os.urandom(16)
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt,
iterations=100000, backend=default_backend())
key = base64.urlsafe_b64encode(kdf.derive(password))
f = Fernet(key)
message = "A really secret message. Not for prying eyes.".encode()
token = f.encrypt(message)
file = open("text_encrypted.txt", "wb")
file.write(token)
file.close()
file = open("text_encrypted.txt", "rb")
data = file.read()
file.close()
token = f.decrypt(data)
file = open("text_decrypted.txt", "wb")
file.write(token)
file.close()
现在,这个方案可以很好地运行,我得到了包含加密和解密信息的两个文件。 如果我删除:
message = "A really secret message. Not for prying eyes.".encode()
token = f.encrypt(message)
file = open("text_encrypted.txt", "wb")
file.write(token)
file.close()
我应该只留下解密代码以便在一个之前已加密的文件上使用,该文件应该可以通过相同的密码进行解密。
显然我可能遗漏了一些微不足道的东西,因为这引发了无效签名和无效令牌的问题。谢谢您的帮助。