Nine spreads: hashes, symmetric and public-key encryption, signatures, key exchange, certificates and TLS, password storage, and the mistakes that break real systems.
"AES-GCM or ChaCha20-Poly1305 for data, X25519 and Ed25519 for keys and signatures, Argon2id for passwords, TLS 1.3 on the wire, and never roll your own."
Use the tabs or the ← → keys. Use vetted libraries in real systems.
$ echo -n "hello" | sha256sum 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824 - $ echo -n "hellp" | sha256sum # one letter later: nothing alike $ sha256sum ubuntu.iso ; sha256sum -c SHA256SUMS # verify a download $ echo -n "msg" | openssl dgst -sha256 -hmac "secretkey" # HMAC: a hash with a key $ openssl dgst -sha3-256 file.bin ; b2sum file.bin # SHA-3, BLAKE2
import hashlib, hmac, secrets h = hashlib.sha256(b"hello").hexdigest() # HMAC: proves the message came from someone with the key and wasn't altered key = secrets.token_bytes(32) tag = hmac.new(key, b"amount=100&to=alice", hashlib.sha256).digest() ok = hmac.compare_digest(tag, hmac.new(key, received, hashlib.sha256).digest()) # constant-time compare!
| Algorithm | Status |
|---|---|
| MD5, SHA-1 | broken for collisions: don't use for security |
| SHA-256 / SHA-512, SHA-3 | good |
| BLAKE2 / BLAKE3 | fast and good |
hash(key + message)"SHA-256 for integrity, HMAC when a key is involved, and constant-time comparison for tags."
# pip install cryptography import os from cryptography.hazmat.primitives.ciphers.aead import AESGCM key = AESGCM.generate_key(bit_length=256) # keep this secret and safe aes = AESGCM(key) nonce = os.urandom(12) # 96-bit, unique per message aad = b"user=42" # authenticated but not encrypted (context) ct = aes.encrypt(nonce, b"my secret note", aad) # ciphertext + 16-byte tag store = nonce + ct # the nonce isn't secret; keep it with the ciphertext pt = AESGCM(key).decrypt(store[:12], store[12:], aad) # raises InvalidTag if tampered with
$ openssl rand -hex 32 # a random 256-bit key $ openssl enc -aes-256-cbc -pbkdf2 -salt -in a.txt -out a.enc # password-based file encryption (quick use) $ age -p -o a.age a.txt ; age -d a.age # modern, simple file encryption $ gpg -c a.txt # passphrase encrypt (GnuPG)
"AEAD with a fresh random nonce per message, keys from a KMS, and envelope encryption for bulk data."
$ openssl genpkey -algorithm ed25519 -out ed.key # private key (guard it) $ openssl pkey -in ed.key -pubout -out ed.pub # public key (share it) $ openssl pkeyutl -sign -inkey ed.key -rawin -in file.txt -out file.sig $ openssl pkeyutl -verify -pubin -inkey ed.pub -rawin -in file.txt -sigfile file.sig $ ssh-keygen -t ed25519 -C "me@laptop" # SSH uses the same idea $ openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out rsa.key
from cryptography.hazmat.primitives.asymmetric import ed25519 priv = ed25519.Ed25519PrivateKey.generate() pub = priv.public_key() sig = priv.sign(b"release-1.4.2.tar.gz sha256:ab12…") pub.verify(sig, b"release-1.4.2.tar.gz sha256:ab12…") # raises InvalidSignature if anything changed
| Algorithm | Use | Notes |
|---|---|---|
| Ed25519 | signatures | small, fast, hard to misuse |
| ECDSA P-256 | signatures, TLS | widely supported |
| RSA 2048–4096 | signatures, encryption | large, slower; use OAEP/PSS padding |
| X25519 | key exchange | next chapter |
"Ed25519 for signatures, RSA only for compatibility with OAEP and PSS, and keys generated and held in a KMS."
Symmetric crypto is fast but needs a shared key. Diffie–Hellman lets two parties derive one over a public channel. Mixed with a signature (so you know who you're talking to), it's the heart of TLS, SSH, Signal and WireGuard.
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.hazmat.primitives import hashes a = X25519PrivateKey.generate(); b = X25519PrivateKey.generate() shared_a = a.exchange(b.public_key()) # Alice computes shared_b = b.exchange(a.public_key()) # Bob computes assert shared_a == shared_b # never use the raw shared secret as a key: derive one with a KDF key = HKDF(algorithm=hashes.SHA256(), length=32, salt=None, info=b"chat v1").derive(shared_a)
$ wg genkey | tee private.key | wg pubkey > public.key # WireGuard: X25519 under the hood
"Ephemeral X25519 for forward secrecy, authenticated by signatures, with keys derived through HKDF."
$ openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null | openssl x509 -noout -subject -issuer -dates -ext subjectAltName $ openssl s_client -connect example.com:443 -tls1_3 -brief </dev/null # protocol + cipher negotiated $ curl -vI https://example.com 2>&1 | grep -E 'SSL|TLS|subject|issuer|expire' $ echo | openssl s_client -connect example.com:443 -showcerts 2>/dev/null | grep -E '^ [0-9] s:' # the chain # your own CA for a lab (never for production trust) $ openssl req -x509 -newkey ed25519 -nodes -keyout ca.key -out ca.crt -days 365 -subj "/CN=Lab CA" $ openssl req -newkey ed25519 -nodes -keyout srv.key -out srv.csr -subj "/CN=app.test" -addext "subjectAltName=DNS:app.test" $ openssl x509 -req -in srv.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out srv.crt -days 90 -copy_extensions copy $ openssl verify -CAfile ca.crt srv.crt $ sudo certbot --nginx -d example.com # free public cert via Let's Encrypt, auto-renew
"TLS 1.3 with automated short-lived certificates, HSTS, and mTLS between internal services."
import secrets, os
token = secrets.token_urlsafe(32) # session IDs, reset tokens, API keys
key = secrets.token_bytes(32)
code = f"{secrets.randbelow(10**6):06d}" # a 6-digit OTP, uniform
# ✘ random.random(), time-seeded RNGs, UUIDv1/v4 from weak sources as secrets
// Node / browser
import { randomBytes, randomUUID } from "node:crypto";
const t = randomBytes(32).toString("base64url");
const bytes = crypto.getRandomValues(new Uint8Array(32)); // Web Crypto in browsers
$ head -c 32 /dev/urandom | base64 $ openssl rand -base64 32 $ aws kms create-key --description "app data key" --key-usage ENCRYPT_DECRYPT $ aws kms generate-data-key --key-id alias/app --key-spec AES_256 # envelope encryption $ vault kv put secret/app api_key=… # HashiCorp Vault
"All secrets from the OS CSPRNG, keys in a KMS with rotation, and one key per purpose."
# pip install argon2-cffi
from argon2 import PasswordHasher
ph = PasswordHasher(time_cost=3, memory_cost=64*1024, parallelism=4) # tune to your hardware
stored = ph.hash("correct horse battery staple") # includes salt + parameters
ph.verify(stored, "correct horse battery staple") # True, or raises VerifyMismatchError
if ph.check_needs_rehash(stored): stored = ph.hash(plain_pw_at_login)
# deriving an encryption key from a passphrase (e.g. an encrypted vault file) import hashlib, os salt = os.urandom(16) key = hashlib.scrypt(b"passphrase", salt=salt, n=2**15, r=8, p=1, dklen=32, maxmem=2**26)
$ python -c "import bcrypt;print(bcrypt.hashpw(b'pw', bcrypt.gensalt(12)))" # bcrypt alternative $ hashcat -m 0 -a 0 hashes.txt rockyou.txt # audit YOUR OWN hashes: how fast would an attacker be?
"Argon2id with a unique salt, tuned cost, rehash on login, and breached-password checks at signup."
hmac.compare_digest# audit your own server's TLS configuration $ nmap --script ssl-enum-ciphers -p 443 yourdomain.example $ testssl.sh yourdomain.example # comprehensive TLS check $ sslyze yourdomain.example # search your own code for crypto smells $ grep -rnE "MD5|SHA1|ECB|Math\.random|verify=False|DES" src/ $ semgrep --config p/security-audit .
"AEAD, constant-time comparisons, no downgrade paths, and scans in CI for weak algorithms and disabled verification."
from cryptography.hazmat.primitives.asymmetric import x25519, ed25519 from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.hazmat.primitives import hashes import os def derive(shared): return HKDF(hashes.SHA256(), 32, None, b"demo-msg-v1").derive(shared) # long-term keys alice_x, bob_x = x25519.X25519PrivateKey.generate(), x25519.X25519PrivateKey.generate() alice_sig = ed25519.Ed25519PrivateKey.generate() # Alice → Bob key = derive(alice_x.exchange(bob_x.public_key())) nonce = os.urandom(12) aad = b"alice->bob" ct = ChaCha20Poly1305(key).encrypt(nonce, b"meet at 6", aad) sig = alice_sig.sign(nonce + ct + aad) # Bob verifies first, then decrypts alice_sig.public_key().verify(sig, nonce + ct + aad) pt = ChaCha20Poly1305(derive(bob_x.exchange(alice_x.public_key()))).decrypt(nonce, ct, aad) print(pt) # b'meet at 6'
"I use a proven protocol with modern defaults, keep keys in a KMS, and never design primitives myself."