我在加密文件中生成一个密钥,并使用Fernet(key).encrypt(contents)加密内容。稍后,我使用相同的密钥,并使用Fernet(key).decrypt(contents)解密内容,但它正在删除所有的内容和加密的文件是空的。为什么会发生这种情况,以及如何使用相同的密钥检索加密的内容?
加密代码:
root_dir = "test_dir"
all_files = []
for file in os.listdir(root_dir):
if os.path.isfile(os.path.join(root_dir, file)):
all_files.append(os.path.join(root_dir, file))
key = Fernet.generate_key()
with open("key.key", "wb") as keyfile:
keyfile.write(key)
for file in all_files:
with open(file, "wb+") as raw_file:
contents = raw_file.read()
enc_contents = Fernet(key).encrypt(contents)
raw_file.write(enc_contents)解密码:
with open("key.key", "rb") as thekey:
code = thekey.read()
for file in all_files:
with open(file, "rb") as enc_file:
contents = enc_file.read()
raw_contents = Fernet(code).decrypt(contents)
print("Raw contents: ", raw_contents)
with open(file, "wb") as enc_file:
enc_file.write(raw_contents)发布于 2022-06-01 19:55:15
当您的加密代码以模式"wb+"打开文件时,它会立即截断文件的现有内容,然后再读取任何内容。尝试使用"rb+",并分别截断:
with open(file, "wb+") as raw_file:
contents = raw_file.read()
raw_file.seek(0)
raw_file.truncate()
enc_contents = Fernet(key).encrypt(contents)
raw_file.write(enc_contents)请注意,如果加密步骤中出现某种错误,这仍然会丢失数据。您可能希望将加密的数据写入一个单独的文件,然后在所有内容都已成功写入之后,将新文件重命名为旧文件。这样的话,如果某些地方出错了,您仍然可以重新尝试旧的纯文本数据。(我想这可能会对安全产生影响,但考虑到明文在您开始加密之前已经在磁盘上,您可能不会让事情变得更糟。)
https://stackoverflow.com/questions/72467306
复制相似问题