"""
File encryption/decryption utility using Fernet (symmetric encryption from cryptography library).
Installation:
pip install cryptography
Usage:
1. Generate a key: generate_key('my_secret.key')
2. Encrypt: encrypt_file('input.txt', 'input.txt.enc', 'my_secret.key')
3. Decrypt: decrypt_file('input.txt.enc', 'input.txt.decrypted', 'my_secret.key')
Notes:
- Files are read/written in binary mode.
- Assumes files fit in memory (for large files, implement chunked streaming).
- Key must match for decryption.
- Backup your key file securely!
"""
from cryptography.fernet import Fernet, InvalidToken
import os
def generate_key(key_path: str = 'secret.key') -> bytes:
"""
Generate a new Fernet key and save it to a file.
Args:
key_path (str): Path to save the key file.
Returns:
bytes: The generated key.
"""
key = Fernet.generate_key()
with open(key_path, 'wb') as key_file:
key_file.write(key)
print(f"Key generated and saved to '{key_path}'")
return key
def encrypt_file(input_path: str, output_path: str, key_path: str = 'secret.key') -> None:
"""
Encrypt a file using the provided key.
Args:
input_path (str): Path to the input file.
output_path (str): Path to save the encrypted file.
key_path (str): Path to the key file.
Raises:
FileNotFoundError: If input or key file not found.
"""
if not os.path.exists(input_path):
raise FileNotFoundError(f"Input file not found: {input_path}")
if not os.path.exists(key_path):
raise FileNotFoundError(f"Key file not found: {key_path}")
with open(key_path, 'rb') as key_file:
key = key_file.read()
fernet = Fernet(key)
with open(input_path, 'rb') as input_file:
data = input_file.read()
encrypted_data = fernet.encrypt(data)
with open(output_path, 'wb') as output_file:
output_file.write(encrypted_data)
print(f"File encrypted: {input_path} -> {output_path}")
def decrypt_file(input_path: str, output_path: str, key_path: str = 'secret.key') -> None:
"""
Decrypt a file using the provided key.
Args:
input_path (str): Path to the encrypted input file.
output_path (str): Path to save the decrypted file.
key_path (str): Path to the key file.
Raises:
FileNotFoundError: If input or key file not found.
InvalidToken: If decryption fails (wrong key or corrupted data).
"""
if not os.path.exists(input_path):
raise FileNotFoundError(f"Input file not found: {input_path}")
if not os.path.exists(key_path):
raise FileNotFoundError(f"Key file not found: {key_path}")
with open(key_path, 'rb') as key_file:
key = key_file.read()
fernet = Fernet(key)
with open(input_path, 'rb') as input_file:
data = input_file.read()
try:
decrypted_data = fernet.decrypt(data)
except InvalidToken as e:
raise InvalidToken("Decryption failed: Invalid key or corrupted data") from e
with open(output_path, 'wb') as output_file:
output_file.write(decrypted_data)
print(f"File decrypted: {input_path} -> {output_path}")
Example Usage:
python
# Generate key
generate_key('mykey.key')
# Encrypt a file
encrypt_file('document.txt', 'document.txt.enc', 'mykey.key')
# Decrypt it back
decrypt_file('document.txt.enc', 'document_decrypted.txt', 'mykey.key')