from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher = Fernet(key)
def encrypt_file(file_path):
with open(file_path, "rb") as f:
content = f.read()
encrypted_content = cipher.encrypt(content)
with open(file_path, "wb") as f:
f.write(encrypted_content)
encrypt_file(file_path)
def decrypt_file(file_path):
with open(file_path, "rb") as f:
encrypted_content = f.read()
with open(file_path, "wb") as f:
decrypted_content = cipher.decrypt(encrypted_content)
f.write(decrypted_content)
decrypt_file(file_path)
I’m new on cryptography so I wonder how can I decrypt a file that was encrypted before? Do I need to use my key to encrypt content of a file?
>Solution :
You need to save the decrypted content to a new file instead of overwriting the original one. Try like this
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher = Fernet(key)
def encrypt_file(file_path):
with open(file_path, "rb") as f:
content = f.read()
encrypted_content = cipher.encrypt(content)
with open(file_path + ".encrypted", "wb") as f: # Save encrypted content to a new file
f.write(encrypted_content)
def decrypt_file(encrypted_file_path, output_file_path):
with open(encrypted_file_path, "rb") as f:
encrypted_content = f.read()
decrypted_content = cipher.decrypt(encrypted_content)
with open(output_file_path, "wb") as f:
f.write(decrypted_content)
# Encrypt file
file_path = "path/to/your/file.txt"
encrypt_file(file_path)
# Decrypt file
encrypted_file_path = "path/to/your/file.txt.encrypted"
output_file_path = "path/to/your/decrypted_file.txt"
decrypt_file(encrypted_file_path, output_file_path)