Encrypt files using Fernet symmetric encryption from cryptography. Derive the key from a user password using PBKDF2HMAC with a salt and 100,000 iterations. Prepend the unencrypted salt to the output file for later decryption.
Assistant
Providing Fernet file encryption with PBKDF2HMAC key derivation
Here's Python code that securely derives a Fernet key from a password with a random salt, encrypts a file's contents, and writes the salt prepended to the ciphertext for later decryption:
python
import base64
import os
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.fernet import Fernet
def derive_key(password: str, salt: bytes) -> bytes:
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100_000,
backend=default_backend()
)
return base64.urlsafe_b64encode(kdf.derive(password.encode()))
def encrypt_file(password: str, input_path: str, output_path: str):
salt = os.urandom(16) # Secure random salt
key = derive_key(password, salt)
fernet = Fernet(key)
with open(input_path, 'rb') as f_in:
plaintext = f_in.read()
ciphertext = fernet.encrypt(plaintext)
with open(output_path, 'wb') as f_out:
f_out.write(salt + ciphertext) # Prepend salt for use in decryption
This method ensures the salt is stored unencrypted at the start of the output file so the same password can be used to derive the key during decryption by extracting the salt first.
You can take a human‑readable password, stretch it with PBKDF2 to 32 bytes, and feed that into Fernet. The salt needs to be random for each encryption and stored alongside the ciphertext so the same key can be re‑derived on decryption.
Here's a minimal example that reads an input file, encrypts it, and writes the salt followed by the Fernet token to an output file:
python
import os
import base64
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.fernet import Fernet
def derive_key(password: str, salt: bytes) -> bytes:
"""Derive a 32‑byte key from the given password and salt."""
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100_000,
)
return base64.urlsafe_b64encode(kdf.derive(password.encode('utf-8')))
def encrypt_file(password: str, infile: str, outfile: str) -> None:
# Generate a fresh random salt for this file
salt = os.urandom(16)
key = derive_key(password, salt)
f = Fernet(key)
# Read the plaintext, encrypt it, and write salt+ciphertext
with open(infile, 'rb') as f_in:
plaintext = f_in.read()
ciphertext = f.encrypt(plaintext)
with open(outfile, 'wb') as f_out:
f_out.write(salt + ciphertext)
# Example usage:
encrypt_file('correct horse battery staple', 'secret.txt', 'secret.enc')
To decrypt, reverse the process: read the first 16 bytes of the encrypted file as the salt, derive the same key with the user's password, and pass the remaining bytes to Fernet.decrypt(). Because the salt is not secret, it's safe to prepend it in cleartext to the output file for later decryption.