Amazon holiday deals See deals →ad

Mets Minor League Blog

Music theory, instruments and musicians

Mets Minor League Blog

Music theory, instruments and musicians

Fernet Encryption Tutorial: A Step-by-Step Recipe

This recipe is a practical, hands-on guide to encrypting and decrypting data using the Fernet symmetric encryption scheme from the cryptography library in Python. It works because Fernet is a high-level, opinionated format that handles key generation, token creation, and verification with built-in safeguards like timestamps and HMAC authentication. By the end, you’ll have a secure, reusable workflow for protecting sensitive strings and files.

Ingredients

  • Python 3.7 or newer (installed on your system)
  • cryptography library (version 3.4 or later) – install via pip install cryptography
  • A terminal or command prompt
  • A text editor or IDE
  • Your secret data (e.g., a password, API key, or a file’s contents)
  • A safe place to store your key (e.g., a password manager, environment variable, or a secure file with restricted permissions)

Instructions

  1. Install the cryptography library. Open your terminal and run: pip install cryptography. If you’re using a virtual environment, activate it first.
  2. Generate a Fernet key. In a Python script or interactive shell, run the following to create a URL-safe base64-encoded 32-byte key:
    from cryptography.fernet import Fernet
    key = Fernet.generate_key()
    print(key.decode())  # Save this key securely!

    This key is the “secret ingredient” – anyone with it can decrypt your data, so store it safely.

  3. Create a Fernet object. Use the key to instantiate a Fernet cipher object:
    cipher = Fernet(key)

    This object will handle encryption and decryption for you.

  4. Encrypt your data. Convert your plaintext (string or bytes) to bytes if needed, then call encrypt():
    plaintext = b"My secret message"
    token = cipher.encrypt(plaintext)
    print(token)  # This is the encrypted token

    The token includes the timestamp, IV, ciphertext, and HMAC signature.

  5. Decrypt the token. To retrieve the original data, call decrypt() with the token:
    decrypted = cipher.decrypt(token)
    print(decrypted.decode())  # Outputs: My secret message

    If the token is tampered with or too old, this will raise an exception.

  6. Handle errors properly. Always wrap decryption in a try-except block to catch InvalidToken (which covers tampering, wrong key, or expired tokens):
    try:
        decrypted = cipher.decrypt(token)
    except Exception as e:
        print("Decryption failed:", e)
  7. Encrypt a file (optional). Read the file in binary mode, encrypt the contents, and write the token to a new file:
    with open('secret.txt', 'rb') as f:
        data = f.read()
    token = cipher.encrypt(data)
    with open('secret.enc', 'wb') as f:
        f.write(token)

    To decrypt, read the token and call decrypt().

Tips

  • Key management is everything. Never hardcode your key in source code. Use environment variables or a dedicated secrets manager. If you lose the key, your data is permanently unrecoverable.
  • Token expiration. Fernet tokens have a default time-to-live (TTL) of 60 seconds if you set it via Fernet(key, ttl=300). For long-term storage, either omit TTL or use a very large value; otherwise, decryption will fail after the TTL.
  • Use bytes consistently. The encrypt() method expects bytes. If you have a string, encode it with .encode() before encrypting and decode after decrypting.
  • Common mistake: using the wrong key. Always double-check that you’re using the same key for encryption and decryption. A single character difference will cause an InvalidToken error.

Serving Suggestions

This recipe is best served as a foundational layer in your application’s security stack. Use it to encrypt database credentials, API tokens, or configuration file values before storing them. You can also integrate it into a CLI tool to encrypt/decrypt files on demand. Pair it with good key rotation policies and access controls for a well-rounded security posture.

Variations

  • Multi-user setup: Instead of sharing one key, generate a separate key per user and encrypt data with a master key that is itself encrypted with each user’s public key (using asymmetric encryption).
  • Password-based key derivation: Use a password and a KDF (like PBKDF2) to derive the Fernet key. This way, you only need to remember a password, but you must store the salt.
  • Encrypting large files: Fernet is not ideal for very large files because it loads the entire file into memory. For large data, consider streaming encryption with a library like cryptography.hazmat.primitives.ciphers in chunks.
  • Adding TTL for time-sensitive data: If you’re encrypting short-lived tokens (e.g., session IDs), set a TTL to automatically expire them.

Storage and Reheating

Encrypted tokens are safe to store anywhere – in a database, file, or even a URL – because they are self-contained and authenticated. They do not expire unless you set a TTL. For long-term storage, keep the key in a secure location (e.g., a hardware security module or a password manager) and back it up. If you need to “reheat” (decrypt) later, ensure your Python environment has the cryptography library installed. Tokens can be stored indefinitely as long as the key is valid and the token hasn’t been tampered with.

Frequently Asked Questions

Q: Can I use Fernet to encrypt a password and then store it in a database?
A: Yes, that’s a common use case. Encrypt the password, store the token, and decrypt when needed. However, for password verification, consider using a one-way hash (like bcrypt) instead, since you never need to retrieve the original password.

Q: What happens if I lose the key?
A: The data is permanently lost. Fernet uses symmetric encryption, so the same key is needed for decryption. There is no backdoor. Always keep backups of your key.

Q: Why do I get an InvalidToken error when decrypting?
A: This can happen if the token was corrupted, the key is wrong, or the token has expired (if you set a TTL). Check the key and ensure the token hasn’t been altered.

Q: Is Fernet secure enough for production use?
A: Yes, Fernet is built on AES-128-CBC and HMAC-SHA256, which are strong cryptographic primitives. It’s designed to be easy to use correctly, making it a good choice for many applications.

Q: Can I encrypt non-text data like images?
A: Absolutely. Fernet works on bytes, so you can encrypt any binary data. Just read the file in binary mode and encrypt the bytes.

Q: How do I rotate keys?
A: Decrypt all data with the old key, then re-encrypt with a new key. This is a manual process; plan for downtime or implement a dual-key system where you decrypt with either key during transition.

Fernet Encryption Tutorial: A Step-by-Step Recipe
Scroll to top