Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to decrypt a file that was encrypted before?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading