Cryptography
Cryptography is a set of transforms with formal guarantees: a cipher turns a message into something unintelligible without a key, a hash compresses data into a fixed fingerprint, and a signature binds an identity to a message. The mathematics is mature and, for the algorithms you should be using, boring in the best way. What actually fails in practice is everything around the mathematics â key generation, key storage, randomness, certificate lifetimes and the human assumption that "encrypted" means "safe". This lesson covers both halves: the primitives, and the engineering that decides whether they help you.
What cryptography promises, and what it does not
Four properties are in play. Confidentiality means only key holders can read the plaintext. Integrity means any modification is detectable. Authenticity means the origin can be proven. Non-repudiation means the signer cannot later deny having signed. Different primitives deliver different subsets: encryption gives you confidentiality and (with authenticated modes) integrity, hashes give you integrity alone, signatures give you authenticity and non-repudiation.
Cryptography does not protect you against a compromised endpoint, a stolen session token, an employee who approves the wrong certificate, or a protocol that uses correct primitives in a broken order. It also does not hide metadata â traffic analysis still reveals who communicates with whom. And it cannot be validated by obscurity: Kerckhoffs's principle says the system must remain secure even if everything except the keys is public. If your design depends on an attacker not knowing your algorithm, the design is already lost.
Symmetric encryption: one key, both directions
Symmetric ciphers use the same key to encrypt and decrypt. They are fast, which is why they protect bulk data â databases, disks, files, TLS record payloads â while asymmetric crypto handles the key exchange that sets them up.
| Algorithm | Key size | Status | Where you meet it |
|---|---|---|---|
| DES | 56-bit | Broken | Legacy smart cards only |
| 3DES | 168-bit | Deprecated | Old payment terminals |
| AES-128/192/256 | 128â256-bit | Secure | Disk encryption, TLS, VPNs |
| ChaCha20-Poly1305 | 256-bit | Secure | Mobile TLS, WireGuard |
| Blowfish / Twofish | 128â448-bit | Mixed | Legacy systems |
Authenticated encryption modes such as AES-GCM and ChaCha20-Poly1305 combine encryption with a tag that detects tampering. Using an unauthenticated mode (AES-CBC without a MAC) and bolting on a separate hash is a classic protocol bug: it lets attackers flip ciphertext blocks and modify plaintext in transit.
from cryptography.fernet import Fernet, MultiFernet
from datetime import datetime, timedelta
import os
# A Fernet key is url-safe base64; generate it once and store it in a secret manager
key = Fernet.generate_key()
cipher = Fernet(key)
record = b'{"account":"AC-4471","balance":"1250.00"}'
token = cipher.encrypt(record)
print("ciphertext:", token[:40], "...")
# Tokens embed a timestamp; decryption tells you how old the message is
plain = cipher.decrypt(token)
print("round trip:", plain == record)
# MultiFernet supports key rotation: re-encrypt with the new key,
# keeping old keys only for decrypting data still in storage.
new_key = Fernet.generate_key()
rotator = MultiFernet([new_key, key])
rotated = rotator.rotate(token)
print("age after rotation:", Fernet(new_key).extract_timestamp(rotated))
Rotation is the part teams skip. A key used forever is a key that will eventually leak, so build re-encryption into your storage layer the day you introduce encryption at all â retrofitting rotation to a table with a hundred million rows is a migration project you do not want.
Key management is the real cryptography
Most public cryptographic key compromises were not breaks of the algorithm. They were predictable nonces reused across messages, keys written into source control, entropy pools that had not been seeded, or certificates renewed three years late. Treat keys as a lifecycle with states: generate, distribute, store, use, rotate, revoke, destroy.
Generation must come from a cryptographically secure random number generator â os.urandom or a hardware source, never random or a timestamp. Storage belongs in a key management service, an HSM, or at minimum a secret manager with access logging; a key in an environment variable in a public repository is effectively published. Distribution needs integrity protection too, or an attacker can substitute their own key during the handshake. And every key needs an owner and an expiry, because unowned keys are never rotated.
Asymmetric encryption and the handshake behind TLS
Public-key cryptography gives you a key pair: a public key you publish and a private key you never share. It solves the distribution problem â anyone can encrypt to you, only you can decrypt â at the cost of being roughly three orders of magnitude slower than symmetric ciphers, and it introduces a different question: how do you know the public key really belongs to the claimed owner? That question is answered by certificates, which we return to below.
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes, serialization
private_key = rsa.generate_private_key(public_exponent=65537, key_size=3072)
public_key = private_key.public_key()
message = b"deploy tag v2.14.0 approved"
# Encrypt to the recipient; only the matching private key can open it
ciphertext = public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None,
),
)
assert private_key.decrypt(
ciphertext,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(), label=None),
) == message
# Sign instead: proves origin and integrity without hiding the message
signature = private_key.sign(
message,
padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH),
hashes.SHA256(),
)
try:
public_key.verify(signature, message,
padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH),
hashes.SHA256())
print("signature valid: message came from the private key holder")
except Exception:
print("signature invalid: message was altered or misattributed")
Two details in that code are load-bearing. OAEP is the padding that makes RSA encryption semantically secure; textbook RSA without padding leaks structure. PSS with a random salt is the modern signing padding â deterministic signatures without a salt leak when the same message is signed twice.
Hashing: integrity, commitments and passwords
A cryptographic hash maps arbitrary input to a fixed-length digest with three properties: pre-image resistance (you cannot find the input from the digest), collision resistance (you cannot find two inputs with the same digest), and the avalanche effect (a one-bit change rewrites the whole digest). Passwords deserve their own paragraph, because using a general-purpose hash for them is a category error.
| Hash | Output | Status | Correct use |
|---|---|---|---|
| MD5 | 128-bit | Broken | Checksums for non-security dedup only |
| SHA-1 | 160-bit | Weak | Legacy compatibility, never for signatures |
| SHA-256 / SHA-512 | 256/512-bit | Secure | Integrity, signatures, HMAC |
| SHA-3 / BLAKE3 | Variable | Secure | Modern integrity checks |
| bcrypt / scrypt / Argon2 | Salted, stretched | Secure | Password storage |
import hashlib, hmac, secrets, time
# Integrity check: content addressing and tamper detection
payload = b"invoice #88213; total 4200.00"
digest = hashlib.sha256(payload).hexdigest()
tampered = b"invoice #88213; total 400.00"
print("untampered matches:", hashlib.sha256(payload).hexdigest() == digest)
print("tampered matches: ", hashlib.sha256(tampered).hexdigest() == digest)
# Message authentication: a shared secret proves both integrity and origin
mac = hmac.new(b"session-signing-key", payload, hashlib.sha256).hexdigest()
print("HMAC-SHA256:", mac[:32], "...")
# Why passwords need stretching: 100k rounds of PBKDF2 beat a plain SHA-256
start = time.time()
hashed = hashlib.pbkdf2_hmac("sha256", b"correct horse battery", b"salt1234", 200_000)
print("200k iterations took %.2fs" % (time.time() - start))
print("unique per user:", secrets.token_hex(16))
The lesson of that last block is economics: a plain SHA-256 of a password runs billions of times per second on a GPU, so a leaked hash table falls in hours. A memory-hard function with a per-user salt and a deliberate iteration count turns the same attack into a cost the attacker must pay per account.
Certificates, PKI and the chain of trust
A public key is only useful if you can attribute it. A certificate is a signed statement binding a public key to a name, issued by a certificate authority (CA) that browsers and operating systems already trust. Verification walks the chain: your certificate signs the key, an intermediate CA signed your certificate, a root CA signed the intermediate, and the root sits in the trust store.
That chain is also the attack surface. A CA that is compromised can mint certificates for any domain, which is why certificate transparency logs, short certificate lifetimes, CAA DNS records that name permitted issuers, and automated renewal (ACME) all exist. In private systems the same logic applies to service identity: mutual TLS with certificates issued by your internal CA replaces shared secrets, and revocation must be designed in â a certificate whose private key has leaked is trusted until it expires unless you actively revoke and check.
Common Mistakes
Rolling your own protocol from correct primitives
Fix: Use established constructions â TLS 1.3, libsodium, an authenticated cipher mode â and let someone else's formal review cover the ordering.
Encrypting data while leaving key rotation impossible
Fix: Store key identifiers with each ciphertext and build re-encryption into migrations before you have data to migrate.
Using SHA-256 or MD5 directly on passwords
Fix: Store Argon2id, scrypt or bcrypt output with a unique salt and a tunable cost factor.
Generating keys from timestamps, Math.random or short seeds
Fix: Use a CSPRNG or an HSM, and never let application code invent entropy.
Issuing multi-year certificates and forgetting them
Fix: Automate renewal with short lifetimes; long-lived certificates turn expiry into an outage and revocation into a fiction.
Key Takeaways
- Encryption, hashing and signatures deliver different properties â decide whether you need confidentiality, integrity, authenticity or all three.
- Symmetric ciphers protect bulk data; asymmetric crypto solves key distribution and signs, then hands off to a fast symmetric session key.
- Authenticated modes such as AES-GCM detect tampering; unauthenticated encryption plus a bolted-on MAC is a common protocol vulnerability.
- Most real-world crypto failures are key-management failures: reused nonces, leaked secrets, missing rotation, stale certificates.
- Passwords need memory-hard stretching and per-user salts because the attacker's cost must be paid per account, not per hash list.
- PKI converts a public key into a trusted identity through a signed chain â and that chain, not the cipher, is what must be defended.