Build a Python File Encryptor: Protect Sensitive Files With Fernet (Full Code)


You back up your files, you lock your laptop, you use strong passwords — and then your notes, your scanned documents and your credential lists sit on disk in plain text, readable by anyone who gets the drive. Encryption fixes that, and Python makes it easy. Let's build a small file encryptor using Fernet, a symmetric encryption scheme from the cryptography library, that locks any file behind a password-derived key. About 70 lines, and you will actually understand every one of them.

How Fernet Works

Fernet uses AES-128 in CBC mode with HMAC-SHA256 for authentication — in plain terms, it encrypts your data and stamps it so any tampering is detected. You never handle the raw AES details yourself; you create a Fernet object from a 32-byte key, and it handles encryption, decryption and tamper-checking. The one rule: never reuse a key, and never store the key next to the encrypted file. We solve that by deriving the key from a password every time.

The Code

import os
import sys
import getpass
from base64 import urlsafe_b64encode
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

SALT_FILE = ".encryptor.salt"

def load_or_create_salt():
    if os.path.exists(SALT_FILE):
        with open(SALT_FILE, "rb") as f:
            return f.read()
    salt = os.urandom(16)
    with open(SALT_FILE, "wb") as f:
        f.write(salt)
    os.chmod(SALT_FILE, 0o600)
    return salt

def derive_key(password, salt):
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=600_000,
    )
    return urlsafe_b64encode(kdf.derive(password.encode()))

def encrypt_file(path, fernet):
    with open(path, "rb") as f:
        data = f.read()
    with open(path + ".enc", "wb") as f:
        f.write(fernet.encrypt(data))
    print(f"Encrypted -> {path}.enc")

def decrypt_file(path, fernet):
    with open(path, "rb") as f:
        data = f.read()
    out = path[:-4] if path.endswith(".enc") else path + ".dec"
    with open(out, "wb") as f:
        f.write(fernet.decrypt(data))
    print(f"Decrypted -> {out}")

def main():
    if len(sys.argv) != 3 or sys.argv[1] not in ("enc", "dec"):
        print("Usage: python3 filecrypt.py enc|dec <file>")
        sys.exit(1)
    password = getpass.getpass("Password: ")
    salt = load_or_create_salt()
    fernet = Fernet(derive_key(password, salt))
    try:
        if sys.argv[1] == "enc":
            encrypt_file(sys.argv[2], fernet)
        else:
            decrypt_file(sys.argv[2], fernet)
    except Exception as e:
        print(f"Failed: {e} (wrong password or corrupted file?)")

if __name__ == "__main__":
    main()

Install the one dependency first: pip install cryptography.

How It Works

  1. Key derivation — your password goes through PBKDF2 with 600,000 iterations of SHA-256 and a random 16-byte salt. That makes brute-forcing the password slow and expensive, even for an attacker with your files. The salt is stored separately in .encryptor.salt with owner-only permissions — it is not secret, it just has to be unique per user.
  2. Encryption — fernet.encrypt() takes your file's bytes and returns ciphertext with a built-in authenticity tag. Change one byte of the ciphertext and decryption refuses to run.
  3. Decryption — the same password derives the same key, and fernet.decrypt() verifies the tag before returning your original bytes. A wrong password gives a clear failure, not garbage output.

Try It

python3 filecrypt.py enc my-notes.txt
python3 filecrypt.py dec my-notes.txt.enc

Encrypt a test file, open the .enc file in a text editor — it is unreadable gibberish — then decrypt it and check the content is back exactly. Now delete the original with shred -u (plain rm leaves recoverable data on disk).

Rules You Must Not Break

  • Don't lose the password. There is no reset, no recovery, no backdoor. Lose it and the file is gone forever. Test the decrypt step before you delete any original.
  • Don't store the salt file with the encrypted files if you are backing them up to the cloud — keep it on a separate device or in your password manager.
  • Don't encrypt files on a system you don't own. This tool protects your own data. Encrypting someone else's files without permission is ransomware, not a project.

A 70-line script, one strong password, and your sensitive files are no longer plain text. That is defense you can actually use today.

Remember: only encrypt and handle files you own or have written permission to handle. Protecting your own data is the whole point — using encryption against someone else's data is a crime.

Comments

Popular Posts