Encrypting and decrypting data in Python

At certain times we need to encrypt data in the backend to protect it. If you are in the Python ecosystem, you have a fantastic library for this: cryptography. Under the hood it uses OpenSSL, so it is fast and secure. On top of that there is Fernet, which is an abstraction layer that makes it very easy to use.

To use it, first add the dependency to your project:

cryptography>=42

Or install it with pip:

pip install cryptography

The next step is critical. You need to generate an encryption key and store it in a safe place. If you lose it, you will not be able to recover the data. And obviously, if someone else gets it, they will be able to decrypt everything. It is worth remembering that it would be a good idea to store it in an environment variable and/or in a secure vault.

To generate it you can use a script:

python -c 'from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())' > encryption_key.txt

Fernet uses symmetric encryption (AES-128-CBC + HMAC-SHA256). The generated 32-byte key is split into two halves: one for encryption and one for authentication. Internally, the key is generated with os.urandom(32) encoded in base64 url-safe.

With that we are ready to work.

Import the Fernet class:

from cryptography.fernet import Fernet

Load our key. Ideally, we will have stored it in an environment variable:

from os import getenv
encryption_key = getenv("ENCRYPTION_KEY").encode()

And we can already encrypt our first text:

fernet = Fernet(encryption_key)
cipher_text = fernet.encrypt(b"Text I want to protect")

To decrypt it, we just need to use the same Fernet object:

plain_text = fernet.decrypt(cipher_text)
print(plain_text.decode())  # "Text I want to protect"

Now let us focus on the case where we want to protect a binary, such as a file. The process is the same, but with files:

# Encrypt a file
with open("original_file.pdf", "rb") as file:
    original_data = file.read()
cipher_data = fernet.encrypt(original_data)
with open("encrypted_file.enc", "wb") as file:
    file.write(cipher_data)

And with this we already have the basics to encrypt and decrypt data. Use it in your database columns, in the files you store, or in whatever you need. Just remember: the security of your data depends on the security of your key. Guard it like gold.

This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.

Will you buy me a coffee?

Comments

There are no comments yet.

Written by Andros Fenollosa

May 18, 2026

2 min of reading

You may also like

Visitors in real time

You are alone: 🐱