简体   繁体   中英

fernet(key).decrypt(value) cleaning all the contents

I'm generating a key in the encryption file and using Fernet(key).encrypt(contents) to encrypt the contents. Later I am using the same key and using Fernet(key).decrypt(contents) to decrypt the content but it's removing all the contents and the encrypted files are left empty. Why is this happening and how can I retrieve the contents encrypted by using the same key?

Code for encryption:

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)

Decryption code:

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)

When your encryption code opens the files in mode "wb+" , it truncates the existing contents of the file immediately, before anything can be read. Try using "rb+" , and truncating separately:

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)

Note that this still can lose data if you have some kind of error crop up in the encryption step. You might want to write the encrypted data to a separate file, and then after everything has been written successfully, rename the new file over the old one. That way, if something goes wrong part way through, you'll still have the old plaintext data to try again with. (I suppose this might have security implications, but given that the plaintext was already on disk before you started encrypting it, you probably can't make things worse.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM