Encrypting and Decrypting Files

In this advanced Python example, we will learn how to encrypt and decrypt files using the Fernet encryption method from the cryptography library. This is useful for:
Protecting sensitive files (passwords, financial data, personal info)
Securing backups before storage
Ensuring confidentiality in file transfers


Installation

Before running the script, install the required library:

pip install cryptography

Code Example: File Encryption and Decryption

from cryptography.fernet import Fernet
import os

# Function to generate a key and save it to a file
def generate_key():
    key = Fernet.generate_key()
    with open("secret.key", "wb") as key_file:
        key_file.write(key)

# Function to load the encryption key from a file
def load_key():
    return open("secret.key", "rb").read()

# Function to encrypt a file
def encrypt_file(file_path):
    key = load_key()
    fernet = Fernet(key)
    
    with open(file_path, "rb") as file:
        file_data = file.read()
    
    encrypted_data = fernet.encrypt(file_data)
    
    with open(file_path + ".enc", "wb") as encrypted_file:
        encrypted_file.write(encrypted_data)

    print(f"File '{file_path}' encrypted successfully!")

# Function to decrypt a file
def decrypt_file(encrypted_file_path):
    key = load_key()
    fernet = Fernet(key)
    
    with open(encrypted_file_path, "rb") as encrypted_file:
        encrypted_data = encrypted_file.read()
    
    decrypted_data = fernet.decrypt(encrypted_data)
    
    original_file_path = encrypted_file_path.replace(".enc", ".dec")
    with open(original_file_path, "wb") as decrypted_file:
        decrypted_file.write(decrypted_data)

    print(f"File '{encrypted_file_path}' decrypted successfully as '{original_file_path}'!")

# Ensure encryption key exists
if not os.path.exists("secret.key"):
    generate_key()
    print("Encryption key generated and saved.")

# Example usage
file_to_encrypt = "example.txt"

# Encrypt the file
encrypt_file(file_to_encrypt)

# Decrypt the file
decrypt_file(file_to_encrypt + ".enc")

How It Works:

  1. Generates an encryption key and stores it in secret.key.
  2. Encrypts a file (example.txt) and saves it as example.txt.enc.
  3. Decrypts the encrypted file back to example.txt.dec.

Expected Output (Console):

Encryption key generated and saved.
File 'example.txt' encrypted successfully!
File 'example.txt.enc' decrypted successfully as 'example.txt.dec'!

Why Use This Approach?

Secure file encryption with a strong key
Prevents unauthorized access to sensitive data
Works with any file type (text, images, documents, etc.)
Useful for secure backups and file transfers

This encryption system ensures your files stay confidential and secure from unauthorized access! 🚀