How to Implement Encryption in Python: A Practical Guide
Encryption is essential for protecting sensitive data in transit and at rest. Python makes it straightforward with the cryptography library, which provides robust, battle-tested implementations. This guide walks you through the core techniques: symmetric encryption, asymmetric encryption, and hashing for password security.
Before writing any code, install the library: pip install cryptography. Always rely on established libraries rather than rolling your own algorithms—this prevents subtle vulnerabilities and ensures compatibility.
Symmetric Encryption with Fernet
Fernet is a high-level symmetric encryption scheme in the cryptography library. It uses AES-128-CBC with HMAC authentication, making it ideal for encrypting files or database fields.
from cryptography.fernet import Fernet
# Generate and store a key
key = Fernet.generate_key()
cipher = Fernet(key)
# Encrypt and decrypt
token = cipher.encrypt(b"Secret data")
plaintext = cipher.decrypt(token)
Store the key securely (e.g., in environment variables or a key management service). Never hardcode it in your source code.
Asymmetric Encryption with RSA
For exchanging data between parties, use RSA. Generate a key pair, share the public key, and keep the private key secret.
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashes
# Generate private key
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()
# Encrypt with public key
ciphertext = public_key.encrypt(
b"Secret data",
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
)
# Decrypt with private key
plaintext = private_key.decrypt(ciphertext, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
RSA is slower than symmetric encryption, so it’s often combined with AES for performance.
Hashing for Passwords
Never store plaintext passwords. Use a dedicated password hashing library like bcrypt or argon2.
import bcrypt
password = b"my_secret"
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password, salt)
# Verify
bcrypt.checkpw(password, hashed)
These libraries automatically add salts and are resistant to brute-force attacks.
Key Management Best Practices
- Rotate keys periodically.
- Separate encryption keys from the data they protect.
- Use environment variables or a vault for key storage.
- Encrypt data before storing or transmitting it.
Implementing encryption in Python is straightforward with the right tools. Focus on using proven libraries, managing keys carefully, and following best practices to keep your data secure.