Symmetric AES for bulk encryption, asymmetric RSA for key exchange, SHA-256 for hashing, HMAC for auth.
Cryptography for Developers
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes, serialization
import hashlib, hmac
# Symmetric encryption (fast, same key)
key = Fernet.generate_key()
cipher = Fernet(key)
token = cipher.encrypt(b"sensitive data")
plain = cipher.decrypt(token)
# Asymmetric encryption (RSA)
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 message",
padding.OAEP(mgf=padding.MGF1(hashes.SHA256()),algorithm=hashes.SHA256(),label=None)
)
# Hashing (one-way, not reversible)
sha256_hash = hashlib.sha256(b"data").hexdigest()
# HMAC (hash + secret key for integrity)
hmac_val = hmac.new(key, message.encode(), hashlib.sha256).hexdigest()
# When to use what:
# Symmetric (AES): encrypt large data, fast
# Asymmetric (RSA): key exchange, digital signatures
# Hash (SHA-256): integrity check, password storage (via bcrypt)
# HMAC: message authentication, webhook signatures