SEC/Lesson 2 of 7/7 min read
Cryptography
Symmetric and asymmetric encryption, AES modes, RSA, Diffie-Hellman and ECC, hashing, MACs, digital signatures, PKI and certificates, the TLS handshake, and password storage.
On this page
Cryptography
Cryptography protects data from adversaries using mathematics. It provides confidentiality (encryption), integrity (hashes, MACs), authentication (MACs, signatures) and non-repudiation (signatures).
Vocabulary: plaintext is encrypted with a key into ciphertext; decryption reverses it. By Kerckhoffs's principle, the algorithm is public; only the key is secret.
Symmetric Encryption
The same key encrypts and decrypts.
- Very fast; used for bulk data.
- Problem: key distribution. Both sides need the key, and n parties need n(n-1)/2 pairwise keys.
AES
AES (Advanced Encryption Standard) is the standard symmetric block cipher: 128-bit blocks, 128, 192 or 256-bit keys. Hardware-accelerated on modern CPUs. Older ciphers like DES (56-bit key, brute-forceable) and 3DES are obsolete. ChaCha20 is a fast stream-cipher alternative on devices without AES hardware.
Block Cipher Mode
A block cipher encrypts one block; the mode defines how to encrypt longer messages.
| Mode | Notes |
|---|---|
| ECB | Each block encrypted independently. Identical plaintext blocks give identical ciphertext, leaking patterns. Never use. |
| CBC | Each block XORed with the previous ciphertext; needs a random IV. No integrity; vulnerable to padding oracle attacks if misused. |
| CTR | Turns the cipher into a stream cipher with a counter; parallelizable. No integrity. |
| GCM | CTR plus an authentication tag. Authenticated encryption (AEAD): confidentiality and integrity together. The default choice. |
Never reuse a nonce with the same key in CTR or GCM: it breaks confidentiality and, for GCM, lets attackers forge messages.
Asymmetric Encryption
Asymmetric encryption (public key cryptography) uses a key pair: a public key anyone may know and a private key kept secret.
- Encrypt with the recipient's public key; only their private key decrypts. Solves key distribution.
- Sign with your private key; anyone verifies with your public key.
- 100 to 1000 times slower than symmetric encryption, so it is used to exchange or protect symmetric keys, not bulk data (hybrid encryption).
RSA
RSA's security rests on the difficulty of factoring the product of two large primes. Keys of 2048 bits are the minimum today; 3072+ for long-term use. Use OAEP padding for encryption and PSS for signatures.
Diffie-Hellman
Diffie-Hellman lets two parties agree on a shared secret over a public channel without ever sending it. Each picks a secret, sends a public value derived from it, and both compute the same shared key. Plain DH has no authentication, so it is vulnerable to man-in-the-middle unless the exchange is signed (as in TLS).
Elliptic Curve Cryptography
Elliptic curve cryptography (ECC) gives the same security as RSA with much smaller keys (a 256-bit ECC key is roughly equal to 3072-bit RSA), so it is faster and lighter. ECDHE (key exchange) and ECDSA or Ed25519 (signatures) are standard in modern TLS and SSH.
Quantum computers running Shor's algorithm would break RSA and ECC; post-quantum algorithms (ML-KEM, ML-DSA) are being deployed, often in hybrid with classical ones.
Cryptographic Hash Function
A cryptographic hash function maps any input to a fixed-size digest. Required properties:
- Pre-image resistance: given a hash, you cannot find an input that produces it.
- Second pre-image resistance: given an input, you cannot find another with the same hash.
- Collision resistance: you cannot find any two inputs with the same hash.
- Avalanche effect: a one-bit change flips about half the output bits.
SHA-256
SHA-256 (SHA-2 family, 256-bit output) is the standard general-purpose hash. SHA-3 and BLAKE2/3 are modern alternatives. MD5 and SHA-1 are broken (practical collisions) and must not be used for security.
Hashing is not encryption: there is no key and it cannot be reversed.
Message Authentication Code
A message authentication code proves a message came from someone holding a shared secret key and was not modified.
HMAC
HMAC combines a hash with a key: HMAC(key, message). Used for API request signing, webhook verification and JWT HS256.
import hmac, hashlib
tag = hmac.new(key, body, hashlib.sha256).hexdigest()
hmac.compare_digest(tag, received_tag) # constant-time comparison avoids timing attacksA plain hash(key + message) is vulnerable to length-extension attacks with SHA-2; use HMAC.
Digital Signature
A digital signature is created by signing a hash of the message with the sender's private key; anyone verifies it with the public key.
- Provides authenticity, integrity and non-repudiation (unlike a MAC, only one party holds the signing key).
- Used for TLS certificates, code signing, software updates, JWT
RS256andES256, and Git commits.
| Hash | MAC | Signature | |
|---|---|---|---|
| Key | None | Shared secret | Private/public pair |
| Integrity | Only against accidents | Yes | Yes |
| Authenticity | No | Yes | Yes |
| Non-repudiation | No | No | Yes |
PKI
A public key alone does not tell you whose it is. A Public Key Infrastructure binds identities to public keys using certificates.
- An X.509 certificate contains a subject (such as
example.com), its public key, a validity period and the issuer's signature. - A Certificate Authority (CA) verifies the identity and signs the certificate.
- Chain of trust: leaf certificate → intermediate CA → root CA. Root certificates are pre-installed in browsers and operating systems.
- Revocation: CRLs and OCSP; in practice, short-lived certificates (Let's Encrypt's 90 days or less) limit the damage of a stolen key.
- Certificate Transparency logs make every issued certificate public, so mis-issuance can be detected.
TLS
TLS (Transport Layer Security, successor of SSL) secures HTTPS and most other protocols. It gives confidentiality, integrity and server authentication (and optionally client authentication with mTLS).
TLS Handshake
TLS 1.3, a single round trip:
- ClientHello: supported cipher suites, a random value, and a key share (ECDHE public value) for likely groups.
- ServerHello: chosen cipher suite and the server's key share. Both sides now derive the session keys.
- The server sends (encrypted) its certificate and a CertificateVerify signature proving it owns the private key, plus Finished.
- The client verifies the certificate chain and hostname, sends Finished, and application data flows encrypted with AES-GCM or ChaCha20-Poly1305.
TLS 1.3 removed weak options (RSA key exchange, CBC, SHA-1, RC4) and supports 0-RTT resumption (with replay risks for non-idempotent requests).
Forward Secrecy
With forward secrecy, each session uses fresh ephemeral (EC)DHE keys. If the server's long-term private key is stolen later, past recorded sessions still cannot be decrypted. TLS 1.3 makes it mandatory.
Password Hashing
Passwords must be stored so that a database leak does not reveal them.
- Never store plaintext or reversibly encrypted passwords.
- Never use fast hashes (MD5, SHA-256) alone: GPUs try billions per second.
- Use a slow, memory-hard password hashing function: Argon2id (preferred), scrypt, or bcrypt, with a tuned work factor.
Salt
A salt is a unique random value per password, stored next to the hash. It makes identical passwords hash differently and defeats precomputed rainbow tables. Modern password hashing functions generate and embed the salt automatically.
A pepper is an extra secret applied to all passwords, kept outside the database (for example in a secrets manager or HSM).
Quick revision
- Symmetric (AES-GCM) for bulk data; asymmetric (RSA, ECC) for key exchange and signatures; combine them (hybrid).
- Never use ECB, DES, MD5 or SHA-1; never reuse a GCM nonce; never roll your own crypto.
- Hash: integrity fingerprint, no key. MAC (HMAC): integrity + authenticity with a shared key. Signature: adds non-repudiation.
- PKI: CAs sign certificates binding names to public keys; trust flows from pre-installed roots.
- TLS 1.3: one round-trip handshake, ECDHE key exchange, mandatory forward secrecy.
- Store passwords with Argon2id, scrypt or bcrypt plus a per-password salt.