To encrypt data in Python, install the cryptography library and use its Fernet class: generate a key, call encrypt() to scramble your data, and decrypt() with the same key to get it back. For passwords, don’t encrypt at all: store a slow, salted hash with hashlib.scrypt from the standard library.
Python makes it easy to protect data, and also easy to protect it the wrong way. Base64 looks scrambled but anyone can reverse it. MD5 is fast, which is exactly what you don’t want for passwords. And homemade ciphers, like the one in 100 Days of Python: Day 008 Caesar Cipher, are fun to write but break in seconds.
This guide shows the right tool for each job, with examples you can run: hashing, password storage, secure tokens, message signatures, symmetric encryption with Fernet, encrypting files, keys from passwords, key rotation, and public-key encryption and signatures. Every example was tested with Python 3.12 and cryptography 50.
Encoding, Hashing, and Encryption: Know the Difference
These three words get mixed up all the time, and the mix-ups cause real security bugs.
| Reversible? | Needs a key? | Use it for | |
|---|---|---|---|
| Encoding (Base64, hex) | Yes, by anyone | No | Turning bytes into text so they can travel safely, never for secrecy |
| Hashing (SHA-256, scrypt) | No, one way only | No (but see HMAC) | Checksums, password storage, detecting changes |
| Encryption (Fernet, AES, RSA) | Yes, with the key | Yes | Keeping data secret while still being able to read it later |
Here’s why encoding isn’t protection:
import base64
encoded = base64.b64encode(b"my secret password")
print(encoded)
print(base64.b64decode(encoded))
b'bXkgc2VjcmV0IHBhc3N3b3Jk'
b'my secret password'
Anyone can decode that. If your config file stores a “Base64-encrypted” password, it stores the password.
Encryption protects confidentiality, and hashing and signatures protect integrity, two of the three goals in the CIA triad.
Hashing With hashlib
A hash function turns any input into a fixed-size fingerprint. The same input always gives the same hash, a tiny change gives a completely different one, and you can’t work backward from the hash to the input. hashlib is part of the standard library:
import hashlib
print(hashlib.sha256(b"hello").hexdigest())
print(hashlib.sha256(b"Hello").hexdigest())
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969
One capital letter changed every character. Use SHA-256 (or SHA-3) for new code; MD5 and SHA-1 are broken for security purposes.
Verify a File With a Checksum
Hashes are perfect for checking that a file wasn’t corrupted or changed, like a download, a backup, or a data export. Reading in chunks keeps memory use low for large files:
import hashlib
from pathlib import Path
def sha256_file(path):
digest = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
digest.update(chunk)
return digest.hexdigest()
Path("report.csv").write_text("region,sales\nWest,1200\nEast,950\n")
print(sha256_file("report.csv"))
3ca05381f3044a62d11caee0c51d296f686266462798140ea54c7e4547801c4f
Save the hash next to the file. If the file changes later, even by one byte, the hash won’t match. This is how download pages let you verify installers, and a good habit for the copies in your 3-2-1 backup.
Storing Passwords the Right Way
Passwords are the one secret you should never encrypt. If you can decrypt them, so can anyone who steals your key. Instead, store a hash, and when a user logs in, hash what they typed and compare.
But a plain SHA-256 isn’t enough. It’s designed to be fast, and attackers can try billions of guesses per second on a graphics card. Password hashing needs two extra things:
- A salt: random bytes stored with each hash, so two users with the same password get different hashes and precomputed tables are useless.
- A slow algorithm: one that takes a fraction of a second per guess on purpose. Python’s standard library includes scrypt:
import hashlib
import hmac
import secrets
def hash_password(password):
salt = secrets.token_bytes(16)
key = hashlib.scrypt(password.encode(), salt=salt, n=2**14, r=8, p=1)
return salt.hex() + ":" + key.hex()
def check_password(password, stored):
salt_hex, key_hex = stored.split(":")
key = hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt_hex), n=2**14, r=8, p=1)
return hmac.compare_digest(key, bytes.fromhex(key_hex))
stored = hash_password("correct horse battery staple")
print(stored[:40] + "...")
print(check_password("correct horse battery staple", stored))
print(check_password("wrong password", stored))
print(hash_password("same") == hash_password("same"))
a2f345ca8426d8eb23e4ceab19aa433e:919337d...
True
False
False
The last line shows the salt at work: the same password hashed twice gives different results. Three details matter:
secrets.token_bytes()generates the salt. Thesecretsmodule uses the operating system’s secure random source; therandommodule is predictable and must never be used for security.hmac.compare_digest()compares in constant time, so an attacker can’t learn anything from how long the comparison takes.- The
n,r, andpsettings control how expensive each hash is. Store them with the hash if you might raise them later.
In a real application, use your framework’s password tools (Django has them built in) or a dedicated library like argon2-cffi or bcrypt, which handle the format and settings for you. The point is the same: salted and slow. Better still, consider letting users skip passwords with passkeys.
Secure Random Tokens With secrets
Password reset links, API keys, and session IDs all need values that can’t be guessed. Use secrets:
import secrets
print(secrets.token_hex(16))
print(secrets.token_urlsafe(32))
f357f57050fda54e62eca5c3a79c097d
GR9T7dwCEd6AqGKI0wZU6p8lyYxfJuZ4DWIcGltBHP8
token_urlsafe() is safe to put in URLs. 32 bytes (256 bits) of randomness is plenty for any token.
Proving a Message Wasn’t Changed With HMAC
A hash tells you if data changed, but an attacker who changes the data can simply recompute the hash. An HMAC mixes a secret key into the hash, so only someone with the key can produce a valid one. Services like Stripe and GitHub sign their webhooks this way:
import hashlib
import hmac
secret = b"shared-secret-key"
message = b'{"order": 1042, "amount": 59.99}'
signature = hmac.new(secret, message, hashlib.sha256).hexdigest()
print(signature)
received = hmac.new(secret, b'{"order": 1042, "amount": 0.01}', hashlib.sha256).hexdigest()
print(hmac.compare_digest(signature, received))
7c5fc6233efbde258213b63f9320994696ac49c717c70f5e23668a4639c75574
False
The receiver recomputes the HMAC with the shared secret and compares. The changed amount produces a different signature, so the request is rejected.
Encrypting Data With Fernet
For encryption you’ll need the cryptography library, the standard choice in Python. Install it inside a virtual environment:
pip install cryptography
Or with uv: uv add cryptography.
Fernet is the library’s high-level recipe for symmetric encryption, meaning the same key encrypts and decrypts. It picks safe algorithms for you (AES-128 in CBC mode with an HMAC-SHA256 signature) and handles the details that are easy to get wrong:
from cryptography.fernet import Fernet
key = Fernet.generate_key()
print(key)
f = Fernet(key)
token = f.encrypt(b"Account number: 1234-5678")
print(token)
print(f.decrypt(token))
b'6VHNBxs7MZD1USPwj5HiwDliGx1xPCT0rfpUCEOz2O4='
b'gAAAAABrEjTyYuwWKq-0KF4qg7x_IjpumyIX1YxlkGoWH1m_VRPp6aoMu7v89DFcAb74yYSKu6FgJrw1A6pgROwKn0ggsabkb4-aHFdq8sKp4MlB6JlGY2A='
b'Account number: 1234-5678'
Your key and token will be different every time you run it. Fernet works with bytes, so encode strings first ("text".encode()) and decode the result (.decode()).
Wrong Keys and Tampering Are Detected
A Fernet token is signed as well as encrypted. Decrypting with the wrong key, or a token that was changed even slightly, raises InvalidToken instead of returning garbage:
from cryptography.fernet import Fernet, InvalidToken
f = Fernet(Fernet.generate_key())
token = f.encrypt(b"Account number: 1234-5678")
wrong = Fernet(Fernet.generate_key())
try:
wrong.decrypt(token)
except InvalidToken:
print("Wrong key: InvalidToken")
tampered = token[:-5] + (b"A" if token[-5:-4] != b"A" else b"B") + token[-4:]
try:
f.decrypt(tampered)
except InvalidToken:
print("Tampered token: InvalidToken")
Wrong key: InvalidToken
Tampered token: InvalidToken
Catch InvalidToken wherever you decrypt data you didn’t just create, and treat it as “this data can’t be trusted.”
Keep the Key Out of Your Code
The encryption is only as safe as the key. Never hard-code it or commit it to Git. Generate it once, store it as an environment variable or in a secrets manager, and load it at runtime, as explained in The Importance of the .env File in Python Projects:
python3 -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
Put the output in your .env file as APP_ENCRYPTION_KEY=..., then:
import os
from cryptography.fernet import Fernet
key = os.environ["APP_ENCRYPTION_KEY"]
f = Fernet(key)
token = f.encrypt("[email protected]".encode())
print(f.decrypt(token).decode())
If you lose the key, the data is gone for good; there’s no recovery. Back the key up somewhere safe and separate from the encrypted data.
Tokens That Expire
Every Fernet token includes the time it was created. Pass ttl (seconds) to decrypt() to reject old tokens, useful for things like password reset links:
import time
from cryptography.fernet import Fernet, InvalidToken
f = Fernet(Fernet.generate_key())
token = f.encrypt(b"reset-password:user42")
print(f.decrypt(token, ttl=60))
time.sleep(2)
try:
f.decrypt(token, ttl=1)
except InvalidToken:
print("Token expired")
b'reset-password:user42'
Token expired
Encrypting Files
Fernet can encrypt any bytes, including whole files. This version reads the file, writes an encrypted .enc copy, and decrypts it again (see Python Basics: Files and Exceptions for working with files):
from pathlib import Path
from cryptography.fernet import Fernet
def encrypt_file(path, key):
data = Path(path).read_bytes()
Path(path + ".enc").write_bytes(Fernet(key).encrypt(data))
def decrypt_file(path, key):
data = Path(path).read_bytes()
return Fernet(key).decrypt(data)
key = Fernet.generate_key()
Path("customers.csv").write_text("name,email\nJane,[email protected]\n")
encrypt_file("customers.csv", key)
print(Path("customers.csv.enc").read_bytes()[:30])
print(decrypt_file("customers.csv.enc", key).decode())
b'gAAAAABrEjT03Hee-Ga_NR3rI3aSxm'
name,email
Jane,[email protected]
Fernet reads the whole file into memory, so it suits files up to a few hundred megabytes. For huge files, encrypt in chunks or use a tool built for it. After encrypting, delete the original if the goal is to keep it secret, and remember that a deleted file may still be recoverable from the disk.
Encrypting With a Password Instead of a Key
Sometimes you want a person to unlock the data with a password they remember, not a key file. A key derivation function (KDF) turns the password and a random salt into a proper key. Here cryptography’s Scrypt does it:
import base64
import os
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
def key_from_password(password, salt):
kdf = Scrypt(salt=salt, length=32, n=2**14, r=8, p=1)
return base64.urlsafe_b64encode(kdf.derive(password.encode()))
salt = os.urandom(16)
key = key_from_password("my long passphrase", salt)
token = Fernet(key).encrypt(b"Wi-Fi password: purple-elephant-42")
# Later: the same password and salt give the same key
same_key = key_from_password("my long passphrase", salt)
print(Fernet(same_key).decrypt(token))
b'Wi-Fi password: purple-elephant-42'
The salt isn’t secret, but you must store it with the encrypted data; without it, even the right password can’t recreate the key. A common pattern is to write the salt at the start of the encrypted file. The protection is only as strong as the password, so use a long passphrase.
Rotating Keys With MultiFernet
Good practice is to replace encryption keys periodically, or right away if one might have leaked. MultiFernet takes a list of keys: it encrypts with the first and tries each one when decrypting. rotate() re-encrypts a token with the newest key:
from cryptography.fernet import Fernet, MultiFernet
old_key = Fernet(Fernet.generate_key())
token = old_key.encrypt(b"encrypted last year")
new_key = Fernet(Fernet.generate_key())
f = MultiFernet([new_key, old_key])
print(f.decrypt(token))
rotated = f.rotate(token)
print(new_key.decrypt(rotated))
b'encrypted last year'
b'encrypted last year'
Add the new key at the front, run rotate() over your stored tokens, then remove the old key once nothing uses it.
Going Lower Level: AES-GCM
Fernet is the right choice most of the time. If you need a specific standard, like AES-256, or must work with data from other systems, use AES-GCM from the same library. It’s still authenticated (tampering is detected), but you manage more yourself:
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
key = AESGCM.generate_key(bit_length=256)
aesgcm = AESGCM(key)
nonce = os.urandom(12)
ciphertext = aesgcm.encrypt(nonce, b"patient ID 88231", b"record-v1")
print(len(ciphertext))
print(aesgcm.decrypt(nonce, ciphertext, b"record-v1"))
32
b'patient ID 88231'
The nonce must be unique for every message encrypted with the same key; reusing one can expose your data. Store the nonce next to the ciphertext (it isn’t secret). The third argument is optional “associated data”: it isn’t encrypted, but it’s authenticated, so decryption fails if it changes. The ciphertext is 16 bytes longer than the message because it includes the authentication tag.
Public-Key Encryption and Digital Signatures
Everything so far uses one shared key. Asymmetric (public-key) cryptography uses a pair: a public key you can give anyone, and a private key you keep secret. It solves the problem of sharing a key with someone you’ve never met, and it powers HTTPS, SSH keys, and VPNs.
Encrypting With RSA
Anyone can encrypt with the public key; only the private key can decrypt:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding, rsa
private_key = rsa.generate_private_key(public_exponent=65537, key_size=3072)
public_key = private_key.public_key()
oaep = padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None,
)
ciphertext = public_key.encrypt(b"meet at 10", oaep)
print(len(ciphertext))
print(private_key.decrypt(ciphertext, oaep))
384
b'meet at 10'
Use OAEP padding, as shown, and keys of at least 2048 bits (3072 is a good default). RSA can only encrypt small messages, a few hundred bytes, so real systems use it to encrypt a random symmetric key, and that key encrypts the actual data.
Signing and Verifying With Ed25519
A digital signature is the reverse: you sign with your private key, and anyone with your public key can check that the message came from you and wasn’t changed. This is the basis of non-repudiation. Ed25519 is fast, modern, and has small keys:
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
private_key = Ed25519PrivateKey.generate()
public_key = private_key.public_key()
release = b"backup-tool v2.1.0"
signature = private_key.sign(release)
print(len(signature))
public_key.verify(signature, release)
print("Signature is valid")
try:
public_key.verify(signature, b"backup-tool v2.1.0 (modified)")
except InvalidSignature:
print("Signature is NOT valid")
64
Signature is valid
Signature is NOT valid
verify() returns nothing on success and raises InvalidSignature on failure, so always run it where an exception stops the process.
Saving and Loading Keys
Keys are usually stored as PEM files. Protect a saved private key with a passphrase:
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
private_key = Ed25519PrivateKey.generate()
pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.BestAvailableEncryption(b"key passphrase"),
)
public_pem = private_key.public_key().public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
print(public_pem.decode())
loaded = serialization.load_pem_private_key(pem, password=b"key passphrase")
print(type(loaded).__name__)
-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAVRYd+v/bo52rr0Wyqiq5fhEupbluYoQK+lJge9vAHkw=
-----END PUBLIC KEY-----
Ed25519PrivateKey
Write pem to a file only you can read, and share public_pem freely.
Which Tool Should I Use?
| You want to… | Use |
|---|---|
| Check a file wasn’t corrupted or changed | hashlib.sha256 |
| Store user passwords | hashlib.scrypt with a salt, or argon2-cffi / bcrypt |
| Generate tokens, API keys, reset links | secrets.token_urlsafe |
| Verify a webhook or message came from someone with a shared secret | hmac with SHA-256 |
| Encrypt data you need to read later | cryptography Fernet |
| Let a person unlock data with a password | Scrypt KDF + Fernet |
| Use AES-256 or work with other systems | cryptography AESGCM |
| Let others send you encrypted data | RSA with OAEP (or a hybrid scheme) |
| Prove who wrote something | Ed25519 signatures |
Common Mistakes to Avoid
- Inventing your own encryption. Custom ciphers and clever XOR tricks are broken easily. Use well-reviewed libraries.
- Calling Base64 encryption. It’s encoding; anyone can reverse it.
- Encrypting passwords, or hashing them with MD5 or plain SHA-256. Use a slow, salted password hash.
- Using
randomfor keys or tokens. Usesecretsoros.urandom(). - Hard-coding keys or committing them to Git. Load them from the environment or a secrets manager.
- Reusing a nonce with AES-GCM. Generate a fresh one for every message.
- Ignoring decryption errors. Catch
InvalidTokenandInvalidSignature, and never fall back to using the data anyway. - Keeping the key next to the data. If both are in the same database or folder, one leak exposes everything.
- Using the “hazmat” layer without need.
cryptography.hazmat(“hazardous materials”) gives low-level building blocks that are easy to misuse. Start with Fernet.
Frequently Asked Questions
What is the best encryption library for Python?
cryptography is the most widely used and actively maintained choice. Its Fernet recipe is the easiest safe way to encrypt data. Older libraries like PyCrypto are unmaintained and shouldn’t be used; PyCryptodome is a maintained alternative if you need algorithms that cryptography doesn’t offer.
Is Fernet secure?
Yes, for typical application data. It uses AES with a 128-bit key plus an HMAC-SHA256 signature, so data is both secret and tamper-proof. If a rule requires AES-256, use AESGCM instead.
Can I decrypt a SHA-256 hash?
No. Hashing is one way. Attackers can only guess inputs and compare hashes, which is why short or common passwords are cracked quickly and why password hashes must be slow and salted.
Where should I store encryption keys?
Outside your code and away from the data: in environment variables for small projects, or in a secrets manager (AWS Secrets Manager, Azure Key Vault, HashiCorp Vault, or your hosting platform’s secrets feature) in production. Keep a secure backup; a lost key means lost data.
Does encryption protect data in a database?
It protects it if the database is stolen or leaked without the key. Many databases also offer built-in encryption at rest; encrypting sensitive fields in your application adds protection even from people who can read the database. See Database Security and Privacy.
Conclusion
Python’s standard library covers hashing (hashlib), password storage (hashlib.scrypt), secure randomness (secrets), and message authentication (hmac). For encryption, add the cryptography library and start with Fernet: generate a key, keep it out of your code, and call encrypt() and decrypt(). Reach for AES-GCM, RSA, or Ed25519 only when you need what they offer. Choose the right tool for each job, let well-tested libraries do the hard parts, and protect your keys as carefully as the data itself.
