Encrypt and Decrypt Files Using Python
Encrypt and decrypt files using the cryptography library's Fernet symmetric encryption.
Requires third-party packages — install first
pip install cryptography
Python code
43 linesimport 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
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
- Use `cryptography.hazmat.primitives.ciphers` for more control over the encryption algorithm.
- 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
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.