Decide what you defend, and from whom, before building defences
A threat model names the asset, the attacker and the budget. Bugs cluster at trust boundaries.
Security is not a feature added at the end. And it does not start with encryption. It starts with a question: what are we defending? Here is a small system: a browser you do not control, your server, your database. Between them run trust boundaries, the lines where data passes from a zone you trust less to one you trust more. Most security bugs live on these lines, because assumptions on one side meet hostility from the other. A threat model answers four questions. What are you protecting? From whom? What do they want? What will you spend? A useful answer is concrete: card data, from outside criminals who want to sell it, with five percent of engineering time. Then walk each component with a checklist such as STRIDE: six kinds of harm to ask about.
Threat modelling · Going deeper
STRIDE
Spoofing, tampering, repudiation, information disclosure, denial of service, elevation of privilege. The categories say what to look for, not what to do. Other frameworks exist (PASTA, LINDDUN, OCTAVE); pick one and use it consistently. A two-year-old threat model is fiction.
Cryptographic primitives
All of cryptography is three operations
Symmetric encryption hides data, asymmetric keys handle identity and key agreement, a hash fingerprints.
Every security protocol you have heard of is built from just three operations. Symmetric encryption: one key locks and the same key unlocks. It is very fast, gigabytes a second. Its problem is obvious: how do two strangers get the same key without anyone overhearing? Asymmetric cryptography answers that. Each party has a pair of keys. The public one can be shown to anyone; the private one never leaves its owner. Anyone can lock or check with the public key; only the owner can unlock or sign. It is about a thousand times slower. A hash turns any input into a short fixed fingerprint, thirty-two bytes. It cannot be run backwards, and changing one bit of input changes the fingerprint completely. One HTTPS connection uses all three: asymmetric once, to agree a key and prove identity; symmetric for the data; a hash on every message.
Cryptographic primitives · Going deeper · 1 of 2
What each primitive does and does not do
Symmetric: AES, or ChaCha20 where AES hardware is absent. Asymmetric: Ed25519 for signatures and X25519 for key exchange are the modern defaults; ML-KEM and ML-DSA (2024) resist future quantum computers. A cryptographic hash resists finding an input for a digest, a second input with the same digest, or any colliding pair.
Cryptographic primitives · Going deeper · 2 of 2
Encrypt and authenticate together
Encryption alone hides data but lets an attacker flip bits undetected. AEAD constructions (AES-GCM, ChaCha20-Poly1305) add a tag so any change is rejected on decryption. The same key and nonce must never encrypt two messages: reuse leaks the plaintexts’ XOR and allows forgeries.
Digital signatures
A signature proves who sent it and that nothing changed
A digital signature: signed with a private key, verifiable by anyone holding the public key.
Take the private and public key and use them for proof. Alice wants Bob to be sure a message is hers. She hashes it to a short fingerprint, then signs the fingerprint with her private key. Out comes a signature of sixty-four bytes. Message and signature travel together, by any route at all. Bob hashes the message he actually received, then runs verify with Alice’s public key. The answer is a single true or false. True means it came from the holder of that private key and not one byte has changed. Change a byte in transit and Bob’s hash differs, so verify says false. Sign with any other key and verify says false. This is how software updates, certificates and login tokens are trusted.
Digital signatures · Going deeper
Hashes that prove membership
A Merkle tree combines leaf hashes pairwise up to a single root. Proving one leaf belongs takes about log₂(N) sibling hashes: twenty for a million leaves. Git, Certificate Transparency logs and BitTorrent use it. A hash chain is the linear case; it only detects tampering, so real chains add a signature or other witness.
Check yourself
Someone changes one character of a signed message on its way to Bob. What happens when Bob verifies?
The signature is bound to the exact bytes. Bob’s hash of the altered message differs from the one Alice signed, so verification fails.
Key exchange
Two strangers can agree on a secret in public
Diffie–Hellman key exchange: both sides derive the same secret from values an eavesdropper can see.
Back to the question symmetric encryption left open: how do two strangers get a shared key over a line everyone can hear? Watch it with small numbers. They agree, in public, on twenty-three and five. Alice picks a secret number, six. Bob picks fifteen. Neither is ever sent. Alice computes five to the sixth, remainder on dividing by twenty-three: eight. She sends eight. Bob computes five to the fifteenth: nineteen. He sends nineteen. Now Alice takes Bob’s nineteen to the power of her six, and gets two. Bob takes Alice’s eight to the power of his fifteen, and gets two. The same secret, and it was never sent. The eavesdropper holds twenty-three, five, eight and nineteen, and with real numbers hundreds of digits long, cannot get from those to the secret.
Key exchange · Going deeper
Key exchange and its gap
Reversing the computation is the discrete-logarithm problem, which is computationally hard at real sizes. Plain Diffie–Hellman does not authenticate: an active attacker can run it separately with each side and sit in the middle. TLS closes this by having the server sign the exchange with a certificate key.
Certificates and PKI
A certificate ties a public key to a name you can check
A certificate is a signed claim “this key belongs to this name”, chained to a root your device already trusts.
Key exchange gives you a secret shared with someone. But is that someone your bank, or an attacker on the same Wi-Fi? The bank presents a certificate: a document saying this public key belongs to bank dot com. Anyone could write that. So it is signed. It is signed by an intermediate authority, whose own certificate comes along with it, and that one is signed in turn. At the end of the chain is a root authority whose public key is already on your device, shipped with the operating system or browser. There are about a hundred. The browser checks every signature up the chain, that the name matches, that the dates are valid and that nothing was revoked. One failure and the connection stops. Then the server proves it holds the matching private key by signing the handshake.
Certificates and PKI · Going deeper · 1 of 2
The chain and its weak point
Certificates follow X.509: subject, public key, issuer, validity, extensions. Any root can sign for any domain, so the model is as weak as its weakest authority. Certificate Transparency requires every certificate to be logged publicly; CAA DNS records declare which authority may issue for a domain.
Certificates and PKI · Going deeper · 2 of 2
TLS 1.3: the three primitives composed
Client and server run an authenticated Diffie–Hellman exchange, derive symmetric session keys, then switch to AEAD. TLS 1.3 needs one round trip and removed the legacy weaknesses. Forward secrecy comes from the throwaway exchange keys: the certificate key only signs, so its later leak exposes no past sessions.
Password storage
Store passwords so that every guess is expensive
A password hash must be slow, memory-hard and salted: argon2id, never a plain fast hash.
Databases leak. So the stored form of a password has to stay useless even in an attacker’s hands. At sign-up, the server generates a random salt for this user, and runs password and salt through a function called argon2id that is built to be expensive: half a second and sixty-four megabytes of memory per attempt. Only the salt and the result are stored. Login repeats the calculation and compares. Now the table is stolen, and the attacker starts guessing. If the passwords were stored with a plain fast hash, one graphics card tries ten billion guesses a second, against every user at once. A dictionary of common passwords falls in seconds. With argon2id and a salt: a few hundred guesses a second, and each user must be attacked separately. The same dictionary takes weeks, per user.
Password storage · Going deeper
Three cost profiles
argon2id and scrypt are memory-hard: every guess must allocate megabytes, and GPU memory bandwidth becomes the bottleneck. bcrypt is iteration-hard only, acceptable at a high cost factor for legacy systems. The per-user salt prevents precomputed tables. Compare results in constant time.
Check yourself
A user table leaks. Which way of storing passwords slows the attacker the most?
A salt stops shared work between users, but SHA-256 still allows billions of guesses a second. argon2id makes each guess cost half a second and 64 MB.
Passkeys and phishing
A passkey cannot be phished; a typed code can
A passkey signs the requesting site’s address along with the challenge, so a look-alike site gets nothing usable.
A password is one factor: something you know. Add a second, something you have, and a leaked password is no longer enough. But the usual second factor has a hole. You are lured to a look-alike site. You type your password and the six-digit code from your phone. The fake site passes both to the real bank within the thirty seconds the code is valid, and the attacker is in. Anything a person types can be typed into the wrong place. A passkey removes the typing. Your device holds a separate private key for each site. At login the bank sends a random challenge, and the device signs it together with the address of the site that asked. On the fake site, that address is the fake one. The real bank sees a signature made for the wrong site and rejects it. Nothing depended on you noticing.
OAuth
Let an app act for you without giving it your password
OAuth hands an app a limited, short-lived token. Authentication and authorisation are different questions.
An app wants to read your calendar, which lives at another service. The bad way is to give the app your password for that service. Here is the right way. The app sends you over to the sign-in service. You log in there, on its own page, and approve one specific permission: read my calendar. Your password goes only to the service that already has it. The service sends the app a one-time code. The app exchanges that code, with proof that it is the same app that started, for an access token valid for minutes to hours. Each request to your data carries the token. Note what the token says: what its holder may do. Not who they are. Who you are is a separate, signed statement. Mixing those two up is the classic identity bug.
OAuth · Going deeper · 1 of 2
Authorisation code flow with PKCE
PKCE binds the code to the app that requested it, so an intercepted code is useless. OIDC adds an id_token, a signed statement about the user, alongside the access token. Authorisation models: roles (RBAC), attributes (ABAC), or capabilities where holding the token is the permission. Policy increasingly lives in code (OPA, Cedar).
OAuth · Going deeper · 2 of 2
Inside a JWT
Three base64url parts: a header naming the algorithm, a payload of claims, and a signature over both. Anyone can read the claims, so no secrets go in. Pitfalls: accepting alg none, letting the token choose its own algorithm, skipping the audience, issuer or expiry checks. Pin the algorithm and issuer at the verifier.
Zero trust
Being inside the network proves nothing: check every request
Zero trust replaces the trusted internal network with identity and policy checked on every call.
For decades, corporate security was a castle and a moat. A firewall around the network, and everything inside trusted everything else. The flaw: one phished laptop is inside. From there the attacker moves sideways, from service to service, and nothing stops them. That sideways movement was the main phase of nearly every large breach of the last decade. Zero trust removes the idea of inside. Every service checks every call: who is asking, from what device, in what context. The same phished laptop now reaches only what that one user was allowed to reach, and its other requests are refused. A VPN that checks you once at the door and then lets you roam is not zero trust. It is the moat.
Zero trust · Going deeper
What zero trust is built from
It is not a product. The pieces are identity-aware proxies, workload identity (SPIFFE, cloud IAM roles), mutual TLS between services, usually via a service mesh, and a policy decision point at every service.
Injection
Injection: data that gets read as code
Injection is untrusted input interpreted as instructions. Placeholders keep data and command apart.
Most web attacks share one shape, and this is its clearest form. The attacker types a strange name: x, a quote mark, OR one equals one. If the program builds its database query by gluing strings together, that quote mark ends the name early, and the rest becomes part of the command. One always equals one, so the query matches every row in the table. The database cannot tell which part the developer wrote and which part the attacker typed. With a placeholder, the command is sent first and fixed. The input arrives separately and can only ever be a value. The query looks for a user literally named x-quote-OR and finds nobody. The same shape recurs everywhere: input read as a script in a web page, as a shell command, and, in the last lesson, as instructions to a language model.
Injection · Going deeper
The OWASP Top 10, and the structural fix
The Top 10 lists the categories behind most real breaches, led by broken access control, cryptographic failures and injection. It is a map for design review, not a checklist. Cross-site scripting comes in reflected, stored and DOM-based forms; context-aware output encoding catches all three, and Content Security Policy is the browser-side backstop.
Check yourself
This code runs with the input shown. What does the database do?
The quote closes the string and OR '1'='1' becomes SQL that is always true. A placeholder would have kept the input a plain value.
CSRF and cookies
Your browser sends your cookies even when an attacker asks
CSRF rides the cookies a browser attaches automatically. SameSite cookies and tokens close it.
One more attack, because it shows that harm does not require stealing anything. You are logged in to your bank in one tab. In another, you open a page the attacker controls. It contains a hidden form addressed to the bank, submitted by a script. Your browser sends the request. Look at it. The origin line says it came from the attacker’s page. But the browser has attached your bank session cookie anyway, because it attaches cookies by where a request is going, not by who caused it. To the bank this is you, logged in, asking for a transfer. Two defences. SameSite cookies, now the default, tell the browser to leave the cookie off requests that begin on another site. And a token: a value placed in the bank’s own pages, which the attacker’s page cannot read and so cannot send.
CSRF and cookies · Going deeper · 1 of 2
The forged request in detail
The attacker never reads the response, since the same-origin policy hides it, but the side effect has already happened. A third defence is checking the Origin header on the server. Other header-level defaults worth shipping: HSTS to lock the browser to TLS, Subresource Integrity for third-party scripts, frame-ancestors against clickjacking.
CSRF and cookies · Going deeper · 2 of 2
SSRF: pivoting through your server
The attacker controls a URL the server fetches (a preview, a webhook, an avatar) and points it at internal addresses, such as the cloud metadata service at 169.254.169.254 that hands out credentials. The fix is an egress proxy that resolves DNS once, blocks private ranges and enforces an allow-list. Hiding endpoints is not a defence.
Summary
Security is built in layers, starting from a threat model
Threat model, three primitives, a few protocols, daily practice. Next: standards, how systems agree.
Stack the lesson up. At the base, a threat model: what you defend, from whom, and the trust boundaries where it will be attacked. On that, three primitives: symmetric encryption, key pairs, and hashes. Composed into a handful of protocols: TLS with certificates to make a connection private and proven, OAuth to delegate, passkeys to log in without anything to phish. And at the top, everyday practice: check every request, keep data out of the command channel, ship safe defaults. The primitives are few and well tested. The failures are almost always in how they are put together.
Summary · Going deeper
The security stack
Foundations come first: without a threat model the rest is busywork. Primitives are few. Protocols are where most engineering effort goes and where most bugs live. Algorithm standards come from NIST (FIPS 197, 180-4, 186-5, and 203 to 205 for post-quantum schemes).
Lesson complete
You finished “Security and Cryptography”
Answer the questions along the way to see your score here.