Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

Encrypt and Decrypt Files Using Python

Encrypt and decrypt files using the cryptography library's Fernet symmetric encryption.

Medium Python 3.9+ Jun 27, 2026 Files & data 1 views 0 copies

Requires third-party packages — install first
pip install cryptography

Python code

43 lines
Python 3.9+
import os
from pathlib import Path
from cryptography.fernet import Fernet

def generate_key(key_file: Path) -> bytes:
    key = Fernet.generate_key()
    key_file.write_bytes(key)
    return key

def load_key(key_file: Path) -> bytes:
    return key_file.read_bytes()

def encrypt_file(input_path: Path, key: bytes, output_path: Path = None) -> Path:
    fernet = Fernet(key)
    encrypted_data = fernet.encrypt(input_path.read_bytes())
    out = output_path or input_path.with_suffix(input_path.suffix + '.enc')
    out.write_bytes(encrypted_data)
    return out

def decrypt_file(encrypted_path: Path, key: bytes, output_path: Path = None) -> Path:
    fernet = Fernet(key)
    decrypted_data = fernet.decrypt(encrypted_path.read_bytes())
    out = output_path or encrypted_path.with_suffix('.dec')
    out.write_bytes(decrypted_data)
    return out

if __name__ == "__main__":
    key_file = Path("secret.key")
    original = Path("example.txt")
    original.write_text("Hello, secure world!")

    key = generate_key(key_file)
    enc_path = encrypt_file(original, key)
    print(f"Encrypted: {enc_path}")

    dec_path = decrypt_file(enc_path, key)
    print(f"Decrypted: {dec_path}")
    print(f"Content: {dec_path.read_text()}")

    os.remove(key_file)
    os.remove(original)
    os.remove(enc_path)
    os.remove(dec_path)

Output

stdout
Encrypted: example.txt.enc
Decrypted: example.txt.enc.dec
Content: Hello, secure world!

How it works

The cryptography.fernet.Fernet class provides symmetric encryption using AES-128-CBC with HMAC authentication. generate_key() creates a random 32-byte key, which must be stored securely for later decryption. encrypt() reads the file as bytes and returns encrypted bytes, while decrypt() reverses the process. Using pathlib.Path for file I/O makes the code concise and cross-platform.

Common mistakes

  • Losing or misplacing the encryption key — without it, decryption is impossible.
  • Using a string instead of bytes for the key; Fernet expects bytes.
  • Overwriting the original file without keeping a backup of the encrypted version.

Variations

  1. Use `cryptography.hazmat.primitives.ciphers` for more control over the encryption algorithm.
  2. Store the key in an environment variable or a secrets manager instead of a file.

Real-world use cases

  • Encrypting sensitive configuration files before uploading them to a shared repository.
  • Securing backup archives before storing them in cloud storage or offsite.
  • Protecting user-uploaded documents in a web application from unauthorized access.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Files & data

Related tutorials and quizzes for this topic.