首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >fernet(键).decrypt(值)清除所有内容

fernet(键).decrypt(值)清除所有内容
EN

Stack Overflow用户
提问于 2022-06-01 19:47:26
回答 1查看 63关注 0票数 0

我在加密文件中生成一个密钥,并使用Fernet(key).encrypt(contents)加密内容。稍后,我使用相同的密钥,并使用Fernet(key).decrypt(contents)解密内容,但它正在删除所有的内容和加密的文件是空的。为什么会发生这种情况,以及如何使用相同的密钥检索加密的内容?

加密代码:

代码语言:javascript
复制
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)

解密码:

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2022-06-01 19:55:15

当您的加密代码以模式"wb+"打开文件时,它会立即截断文件的现有内容,然后再读取任何内容。尝试使用"rb+",并分别截断:

代码语言:javascript
复制
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)

请注意,如果加密步骤中出现某种错误,这仍然会丢失数据。您可能希望将加密的数据写入一个单独的文件,然后在所有内容都已成功写入之后,将新文件重命名为旧文件。这样的话,如果某些地方出错了,您仍然可以重新尝试旧的纯文本数据。(我想这可能会对安全产生影响,但考虑到明文在您开始加密之前已经在磁盘上,您可能不会让事情变得更糟。)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72467306

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档