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)