What is cryptography, and what are its main goals?
KnownRevise
Cryptography is the science of protecting information and communications against adversaries using mathematical techniques, so that only intended parties can read or change data and its origin can be trusted. Its main goals: - Confidentiality: only authorised parties can read the data. Achieved with encryption. - Integrity: any change to the data is detected. Achieved with hashes, MACs and authenticated encryption. - Authentication: you can verify who sent the data or who you are talking to. Achieved with MACs, digital signatures and certificates. - Non-repudiation: a signer cannot credibly deny having signed. Achieved with digital signatures, because only the signer holds the private key.
Modern cryptography builds these from a few primitives: symmetric ciphers (AES, ChaCha20), hash functions (SHA-2, SHA-3), MACs (HMAC), public-key algorithms (RSA, elliptic curves, post-quantum schemes) and secure random number generators. These are combined into protocols such as TLS, SSH and Signal.
Read full answerHide full answer
Applies tomodern applied cryptography (concepts are algorithm-independent)
SHA-256 (with a trusted reference), HMAC, AEAD tags
Authentication
Who sent it / who am I talking to?
HMAC with a shared key, digital signatures, certificates, challenge-response
Non-repudiation
Can the sender deny it?
Digital signatures (Ed25519, ECDSA, RSA-PSS) with trusted timestamps
Availability is sometimes listed with these, as part of the CIA triad, but cryptography helps with it only indirectly; it is mostly an engineering concern.
Example: How TLS Combines the Goals
1. Key exchange (ECDHE) -> shared secret, never sent over the network
2. Server certificate + signature -> authentication of the server (and optionally the client)
3. Key derivation (HKDF) -> separate symmetric keys for each direction
4. AEAD encryption (AES-GCM) -> confidentiality + integrity for every record
Core Building Blocks
Primitive
Purpose
Examples
Symmetric encryption
Fast bulk encryption with a shared key
AES-256-GCM, ChaCha20-Poly1305
Asymmetric encryption and key exchange
Establish secrets between strangers
X25519, ECDH, RSA-OAEP, ML-KEM (post-quantum)
Hash functions
Fingerprints of data
SHA-256, SHA-3, BLAKE2/3
MACs
Integrity and authenticity with a shared key
HMAC-SHA256, Poly1305
Digital signatures
Integrity, authenticity, non-repudiation
Ed25519, ECDSA, RSA-PSS, ML-DSA (post-quantum)
Key derivation and password hashing
Derive keys; store passwords safely
HKDF; Argon2id, scrypt, bcrypt
Random number generation
Keys, nonces, salts
OS CSPRNG (/dev/urandom, secrets in Python)
Kerckhoffs’s Principle
A system should stay secure even if everything except the key is public. Security must come from secret keys and well-studied, public algorithms, never from hiding the algorithm (“security through obscurity”).
Pitfalls
Inventing your own algorithms or protocols instead of using vetted libraries (libsodium, the platform’s TLS).
Encryption without integrity: unauthenticated modes let attackers modify ciphertexts. Use AEAD.
Poor key management: hard-coded keys, no rotation, keys stored next to the data.
Weak randomness: random instead of a CSPRNG.
Interview Tips
Name the goals: confidentiality, integrity, authentication and non-repudiation.
Map each goal to mechanisms: encryption, MACs and hashes, signatures.
Mention Kerckhoffs’s principle and “don’t roll your own crypto”.
2
Explain the difference between symmetric and asymmetric cryptography.
KnownRevise
Symmetric cryptography uses one shared secret key for both encryption and decryption (or for creating and checking a MAC). It is very fast and suits bulk data: AES, ChaCha20, HMAC. Its problem is key distribution: both sides must already share the key secretly, and n parties need about n²/2 keys. Asymmetric (public-key) cryptography uses a key pair: a public key anyone may know and a private key only the owner holds. Data encrypted with the public key can only be decrypted with the private key, and signatures made with the private key can be verified with the public key. It solves key exchange and digital signatures between strangers, but is much slower and works on small inputs: RSA, elliptic curves (X25519, Ed25519, ECDSA), and post-quantum schemes (ML-KEM, ML-DSA). Real systems use both, in hybrid cryptography: asymmetric methods to agree on or deliver a symmetric key, then symmetric encryption for the data. TLS, SSH, PGP and Signal all work this way.
Read full answerHide full answer
Applies tomodern cryptographic practice
Comparison
Aspect
Symmetric
Asymmetric
Keys
One shared secret key
Public and private key pair
Speed
Very fast (often hardware-accelerated, GB/s)
Hundreds to thousands of times slower
Key size for about 128-bit security
128-bit AES key
3072-bit RSA or 256-bit elliptic-curve key
Main uses
Bulk encryption, MACs, disk and database encryption
Key exchange, digital signatures, encrypting small secrets
Key distribution
Hard: needs a secure channel beforehand
Public keys can be shared openly (but must be authenticated)
In TLS 1.3 there is no key wrapping: both sides run an ephemeral Diffie-Hellman exchange (X25519) to derive the symmetric keys, and the server signs the handshake to prove its identity.
The Remaining Problem With Public Keys
Public keys need not be secret, but they must be authentic: an attacker who swaps in their own public key can read the traffic (a man-in-the-middle attack). This is solved with certificates and PKI, key fingerprints checked out of band (SSH), or trust on first use.
Encrypting large data directly with RSA: it is slow, size-limited and dangerous with bad padding.
Sharing symmetric keys widely, so any holder can decrypt and forge.
Trusting public keys without verifying them.
Old padding schemes (RSA PKCS#1 v1.5 encryption); prefer OAEP or modern key-exchange schemes.
Interview Tips
Contrast one shared key with a key pair, and speed with key distribution.
Explain hybrid encryption with TLS as the example.
Mention authenticating public keys with certificates.
3
What is a cryptographic hash function, and what properties must it have?
KnownRevise
A cryptographic hash function maps input of any length to a fixed-size output (the digest, for example 256 bits for SHA-256). It is deterministic, fast to compute, and designed so the output looks random and reveals nothing useful about the input. To be cryptographically secure it must have: - Preimage resistance (one-wayness): given a digest h, it is infeasible to find any input x with H(x) = h. - Second-preimage resistance: given an input x, it is infeasible to find a different x′ with H(x′) = H(x). - Collision resistance: it is infeasible to find any two different inputs with the same digest. Because of the birthday bound, this takes about 2^(n/2) work for an n-bit hash.
Good hash functions also show the avalanche effect: changing one input bit flips about half the output bits. Recommended functions are SHA-256 and SHA-512 (SHA-2), SHA-3, and BLAKE2 or BLAKE3. MD5 and SHA-1 are broken for collision resistance.
Read full answerHide full answer
Applies toSHA-2, SHA-3 and BLAKE families (Python 3.12 `hashlib` example)
Code Example: Determinism, Fixed Size and Avalanche
import hashlib
def sha256_bits(data):
return int.from_bytes(hashlib.sha256(data).digest(), "big")
a = b"transfer 100 to alice"
b = b"transfer 900 to alice" # one character different
print(hashlib.sha256(a).hexdigest()[:32]) # 766e90601b2e01f7c7a633d6368a07a5
print(hashlib.sha256(b).hexdigest()[:32]) # eb9535686c306af9c27094fd36a17273
changed = bin(sha256_bits(a) ^ sha256_bits(b)).count("1")
print(f"{changed} of 256 output bits changed") # 116 of 256: close to half (avalanche effect)
# Same input always gives the same digest (deterministic), any input length gives 256 bits
print(len(hashlib.sha256(b"x" * 10_000_000).digest()) * 8, "bits") # 256 bits
The Security Properties
Property
Attacker’s task
Generic cost for an n-bit hash
Why it matters
Preimage resistance
Find x such that H(x) = h
About 2^n
Hashes of secrets do not reveal them
Second-preimage resistance
Given x, find x′ ≠ x with H(x′) = H(x)
About 2^n
A signed or published document cannot be swapped
Collision resistance
Find any x ≠ x′ with H(x) = H(x′)
About 2^(n/2) (birthday bound)
Digital signatures and certificates rely on it
Collision resistance implies second-preimage resistance, and it is the hardest property to keep: it is the one MD5 and SHA-1 lost. Because of the birthday bound, SHA-256 gives 128-bit collision security.
Common Hash Functions
Function
Output
Status
MD5
128 bits
Broken: practical collisions; never use for security
Password storage, but only through slow, salted password hashing (Argon2id, scrypt, bcrypt), never a plain fast hash.
Pitfalls
Plain SHA-256 for passwords: far too fast, so brute force is cheap. Use a password hashing function.
H(secret || message) as a MAC: vulnerable to length-extension attacks with SHA-2. Use HMAC.
MD5 or SHA-1 for signatures or certificates.
Truncating hashes too far, which reduces collision resistance.
Interview Tips
Define it: any input → fixed output, deterministic, one-way.
Name the three resistance properties and the birthday bound.
Mention broken (MD5, SHA-1) versus recommended (SHA-2, SHA-3, BLAKE), and not for passwords on their own.
4
Describe the concept of public key infrastructure (PKI).
KnownRevise
Public key infrastructure (PKI) is the system of policies, roles, software and procedures that lets people trust that a public key really belongs to a particular identity, such as a website, person, device or service. Its core is the digital certificate (X.509): a document binding a subject’s identity to a public key, with a validity period and permitted uses, signed by a certificate authority (CA). Trust flows down a chain: - root CAs are trusted by operating systems and browsers (trust stores); - they sign intermediate CAs; - intermediate CAs sign end-entity (leaf) certificates.
A relying party, such as a browser, validates the chain up to a trusted root and checks the name, validity dates, key usage and revocation status. PKI also covers registration (verifying identity before issuing, via a registration authority), revocation (CRLs, OCSP, short-lived certificates), certificate transparency logs, and the protection of CA keys in HSMs.
Read full answerHide full answer
Applies toX.509 PKI (RFC 5280), the public Web PKI and private enterprise PKIs
Components
Component
Role
Certificate authority (CA)
Issues and signs certificates; root CAs are offline and protected in HSMs
Intermediate CA
Issues day-to-day certificates, so the root key stays offline
Registration authority (RA)
Verifies identity before issuance (domain control, organisation checks)
Sets of trusted root certificates in operating systems, browsers and runtimes
Revocation
CRLs, OCSP (with stapling), and increasingly short certificate lifetimes
Certificate Transparency (CT)
Public append-only logs of issued certificates, to detect mis-issuance
Policies
Certificate policies and practice statements; CA/Browser Forum baseline requirements
The Chain of Trust
Root CA (self-signed, in the trust store)
signs -> Intermediate CA certificate
signs -> Leaf certificate: CN/SAN = shop.example.com, public key, valid 90 days
Browser validation:
1. leaf signature verifies with the intermediate's public key
2. intermediate signature verifies with the root's public key
3. root is in the trust store
4. shop.example.com matches the SAN; dates valid; key usage = server auth; not revoked
Your own policies; you distribute the root to clients
Pitfalls
Expired certificates causing outages: automate renewal and monitor expiry.
Private keys stored insecurely or shared between many servers.
Disabling certificate validation in clients (verify=False), which removes all protection against man-in-the-middle attacks.
Missing intermediate certificates on servers, so some clients fail.
Weak revocation checking, which is why short-lived certificates are increasingly preferred.
Interview Tips
Define PKI as trust in the binding between identities and public keys.
Explain certificates, CAs, the chain of trust and validation steps.
Mention revocation, Certificate Transparency, ACME automation and private PKI for mTLS.
5
What is a digital signature, and how does it work?
KnownRevise
A digital signature is a value computed from a message with the signer’s private key. Anyone with the matching public key can check it. A valid signature proves: - authenticity: the holder of that private key produced it; - integrity: the message has not changed since signing; - non-repudiation: the signer cannot credibly deny it, because nobody else has the key.
The process: - Signing: hash the message (for example SHA-256), then apply the signature algorithm to the digest with the private key: Ed25519, ECDSA or RSA-PSS (or ML-DSA for post-quantum security). - Verifying: recompute the hash and use the public key to check that the signature matches it.
Read full answerHide full answer
Changing a single bit of the message, or using a different key, makes verification fail. To know whose public key it is, signatures rely on certificates and PKI, or on keys distributed in advance.
Applies to: Ed25519, ECDSA, RSA-PSS (and ML-DSA, FIPS 204)
How It Works
Signer (private key) Verifier (public key)
digest = SHA-256(message) digest' = SHA-256(message received)
signature = Sign(private_key, digest) ----> Verify(public_key, digest', signature)
message + signature -> valid only if message unchanged AND
signature made with the matching private key
Blockchains: transactions are signed with ECDSA or Schnorr signatures.
Passkeys and WebAuthn: the device signs a login challenge.
Pitfalls
ECDSA nonce reuse: two signatures with the same nonce reveal the private key (the PlayStation 3 signing key was broken this way).
Signing without context: the same key used for different purposes allows cross-protocol attacks. Separate keys, or include a domain label.
Not checking who owns the public key.
Weak hashes (MD5, SHA-1) in the signature.
Interview Tips
Explain hash then sign with the private key; verify with the public key.
State the guarantees: integrity, authenticity and non-repudiation.
Name Ed25519, ECDSA and RSA-PSS, and contrast signatures with MACs.
6
What is a nonce, and how is it used in cryptography?
KnownRevise
A nonce (“number used once”) is a value that must never repeat for the same key or context. It is used to make every operation unique, so that: - encrypting the same message twice gives different ciphertexts; - old messages cannot be replayed; - keystreams or signature randomness are never reused.
Depending on the algorithm, a nonce may need to be unique (a counter is fine, as in AES-GCM and ChaCha20-Poly1305) or unique and unpredictable (random, as in CBC initialisation vectors and ECDSA’s per-signature value). Nonces are usually not secret and travel with the ciphertext. Reusing a nonce can be catastrophic: with stream ciphers and GCM it reveals the XOR of plaintexts and lets attackers forge messages; with ECDSA it reveals the private key.
import hashlib
import secrets
def keystream(key, nonce, length):
# Toy counter-mode keystream: SHA-256(key || nonce || counter) blocks
out = b""
counter = 0
while len(out) < length:
out += hashlib.sha256(key + nonce + counter.to_bytes(8, "big")).digest()
counter += 1
return out[:length]
def encrypt(key, nonce, plaintext):
return bytes(p ^ k for p, k in zip(plaintext, keystream(key, nonce, len(plaintext))))
key = secrets.token_bytes(32)
p1, p2 = b"salary: 50000 USD", b"salary: 92000 USD"
# Correct: a fresh nonce per message gives unrelated ciphertexts
n1, n2 = secrets.token_bytes(12), secrets.token_bytes(12)
print(encrypt(key, n1, p1) != encrypt(key, n2, p1)) # True: same message, different output
# Wrong: reusing a nonce lets an attacker cancel the keystream
nonce = secrets.token_bytes(12)
c1, c2 = encrypt(key, nonce, p1), encrypt(key, nonce, p2)
leak = bytes(a ^ b for a, b in zip(c1, c2))
recovered = bytes(x ^ y for x, y in zip(leak, p1)) # attacker knows p1, learns p2
print(recovered) # b'salary: 92000 USD'
This uses a toy keystream for illustration, but real stream ciphers and counter modes (AES-CTR, AES-GCM, ChaCha20) behave the same way. With a repeated nonce, the keystream repeats, so the two ciphertexts XOR to the two plaintexts XORed together. Knowing or guessing one plaintext reveals the other.
Where Nonces Appear
Context
Name
Requirement
AES-GCM
96-bit nonce or IV
Unique per key (counter or random; random only up to about 2³² messages per key)
ChaCha20-Poly1305
96-bit nonce
Unique per key
XChaCha20-Poly1305
192-bit nonce
Unique; large enough that random nonces are safe
AES-CBC
128-bit IV
Unpredictable (random)
ECDSA and DSA signatures
Per-signature value k
Secret, unique and uniformly random, or deterministic (RFC 6979); reuse leaks the key
Random per response, to allow specific inline scripts
Blockchains (proof of work)
Nonce
Value varied to find a valid block hash
Generating Nonces
Strategy
Pros
Cons
Counter
Guaranteed unique, simple
Must keep state reliably; dangerous after restores or with several senders
Random (from a CSPRNG)
Stateless
Collision risk if too many messages with 96-bit nonces
Random with large nonces (XChaCha20)
Stateless and safe
Needs algorithm support
Misuse-resistant AEAD (AES-GCM-SIV)
Nonce reuse only reveals whether two messages were equal
Slightly slower
Nonce, IV and Salt
Term
Purpose
Secret?
Nonce
Uniqueness per operation
No
IV (initialisation vector)
Starting state for a mode; often must be random
No
Salt
Makes hashes or derived keys unique per user or context
No
Key
Provides the security
Yes
Pitfalls
Fixed or zero nonces in code (“we’ll fix it later”).
Random 96-bit nonces for billions of messages under one key; rotate keys or use XChaCha20.
Counter resets after a restart, a VM snapshot restore, or a backup restore.
Weak randomness for ECDSA; prefer Ed25519 or deterministic ECDSA.
Interview Tips
Define a nonce as a “number used once” per key, usually public.
Explain the consequences of reuse (keystream reuse, GCM forgeries, ECDSA key leaks).
Distinguish unique versus unpredictable requirements, and nonce, IV and salt.
7
What does it mean for a cryptographic algorithm to be “computationally secure”?
KnownRevise
An algorithm is computationally secure if breaking it is theoretically possible but practically infeasible: every known attack needs far more time, computing power or memory than any realistic adversary has, and the work grows exponentially with the key size. For example, finding a 128-bit AES key by brute force takes on the order of 2¹²⁸ trials, far beyond all the computers on Earth for billions of years. This contrasts with unconditional (information-theoretic) security, as in the one-time pad, which holds even against unlimited computing power, but is rarely practical. Almost all real cryptography, including AES, RSA, elliptic curves, SHA-2 and post-quantum schemes, is computationally secure. It rests on hardness assumptions (factoring, discrete logarithms, lattice problems) and on decades of public cryptanalysis. Modern definitions are formal: no efficient (polynomial-time) adversary succeeds with more than negligible probability. Security levels are stated in bits; 128 bits is the common target.
Read full answerHide full answer
Applies tomodern cryptography (security definitions and parameter choices)
Computational Versus Unconditional Security
Computationally secure
Unconditionally secure
Holds against
Adversaries with realistic resources
Adversaries with unlimited computation
Basis
Hardness assumptions plus cryptanalysis
Information theory
Key requirements
Short keys (128–256 bits) reused for many messages
Keys as long as all messages, used once
Examples
AES, ChaCha20, RSA, ECC, SHA-256, ML-KEM
One-time pad, Shamir secret sharing, some MACs
Practicality
High
Limited
What “Infeasible” Means in Numbers
Work
Rough meaning
2⁶⁴
Within reach of large organisations (SHA-1 collisions cost about 2⁶³)
2⁸⁰
Considered too low for new systems
2¹¹²
Minimum acceptable today (NIST)
2¹²⁸
Standard target; infeasible for classical computers
2²⁵⁶
Margin against future advances, including Grover’s quantum search on symmetric keys
Security Levels and Key Sizes
Security level
Symmetric
Hash (collision)
RSA
Elliptic curve
112 bits
3DES (legacy)
SHA-224
2048
224-bit
128 bits
AES-128
SHA-256
3072
256-bit (P-256, Curve25519)
192 bits
AES-192
SHA-384
7680
384-bit
256 bits
AES-256
SHA-512
15360
521-bit
These are approximate equivalences, following NIST SP 800-57.
Formal Definitions
Modern cryptography defines security with games played against an adversary. For example, IND-CPA (indistinguishability under chosen-plaintext attack): the adversary chooses two messages, receives an encryption of one of them, and must guess which. A scheme is secure if every probabilistic polynomial-time adversary wins with probability at most ½ plus a negligible amount. Reduction proofs show that breaking the scheme would solve a problem believed to be hard.
More computing power over time (Moore’s law, specialised hardware).
Quantum computers: Shor’s algorithm breaks RSA and ECC; Grover’s algorithm halves the bit-security of symmetric keys. Hence post-quantum migration.
Implementation flaws: side channels, bad randomness, misuse. These are usually easier than attacking the mathematics.
Pitfalls
Equating “no known attack” with “proven secure”: security depends on assumptions.
Using outdated parameters, such as 1024-bit RSA or SHA-1.
Ignoring the data’s lifetime: data that must stay secret for 20 years needs more margin (“harvest now, decrypt later”).
Interview Tips
Define it as “breakable in theory, infeasible in practice” with realistic resources.
Contrast it with unconditional security (the one-time pad).
Mention bit security levels, hardness assumptions and quantum threats.
8
Describe the concept of perfect secrecy and name an encryption system that achieves it.
KnownRevise
Perfect secrecy (Claude Shannon, 1949) means the ciphertext reveals absolutely nothing about the plaintext, even to an attacker with unlimited computing power. Formally, for every plaintext m and ciphertext c, P(M = m | C = c) = P(M = m): seeing the ciphertext does not change the attacker’s knowledge at all. The classic system that achieves it is the one-time pad (OTP): XOR the message with a key that is truly random, at least as long as the message, kept secret, and never reused. Every possible plaintext of that length is equally consistent with the ciphertext, because for any candidate plaintext there is exactly one key that produces it. Shannon proved that perfect secrecy requires a key space at least as large as the message space, so keys must be as long as the data. That makes key distribution impractical for most uses, which is why real systems use computationally secure ciphers such as AES.
import secrets
def xor(data, key):
return bytes(d ^ k for d, k in zip(data, key, strict=True))
message = b"ATTACK AT DAWN"
key = secrets.token_bytes(len(message)) # truly random, as long as the message, used once
ciphertext = xor(message, key)
print(xor(ciphertext, key)) # b'ATTACK AT DAWN'
# Perfect secrecy: for ANY plaintext of the same length there is a key that explains the ciphertext
other = b"RETREAT AT TEN"
fake_key = xor(ciphertext, other)
print(xor(ciphertext, fake_key)) # b'RETREAT AT TEN', so the ciphertext reveals nothing
# Reusing the key breaks it: XOR of two ciphertexts equals XOR of the two plaintexts
c2 = xor(b"HOLD THE LINE!", key)
print(xor(ciphertext, c2) == xor(message, b"HOLD THE LINE!")) # True
The second print shows why it is perfectly secret: for any plaintext of the same length there is a key that explains the ciphertext, so an attacker cannot tell which message was sent. The last line shows why key reuse destroys the guarantee.
Requirements of the One-Time Pad
Requirement
If violated
Key is truly random (uniform)
Patterns in the key leak information about the plaintext
Key is at least as long as the message
Repeated key segments behave like a Vigenère cipher, which frequency analysis breaks
Key is used only once
XOR of two ciphertexts equals XOR of the plaintexts (the Venona project exploited this)
Key is kept secret and destroyed after use
Obviously breaks everything
What Perfect Secrecy Does Not Give
Integrity: an attacker can flip bits in the ciphertext and flip the same bits in the plaintext (malleability). Add an information-theoretic MAC if integrity is needed.
Hiding the message length.
Protection against key theft or poor key handling.
Perfect Secrecy Versus Computational Security
One-time pad
AES-256-GCM
Security type
Unconditional (perfect secrecy)
Computational
Key size
Equal to all data ever sent
256 bits for vast amounts of data
Key reuse
Forbidden
Allowed (with unique nonces)
Integrity
None by itself
Built in (AEAD tag)
Practical use
Rare: diplomatic hotlines historically, some niche systems
Stream ciphers imitate the one-time pad with a short key that expands into a long pseudorandom keystream, giving computational rather than perfect security.
Quantum key distribution (QKD) aims to distribute one-time-pad-sized keys securely, but it needs special hardware and authenticated channels.
Secret sharing (Shamir) also has information-theoretic security: fewer than the threshold number of shares reveal nothing.
Pitfalls
Calling any XOR cipher a “one-time pad” when the key is short, pseudorandom or reused.
Using a PRNG (random) to generate pads.
Forgetting integrity.
Interview Tips
Define perfect secrecy as P(m | c) = P(m): the ciphertext reveals nothing.
Name the one-time pad and its four requirements.
Explain Shannon’s key-length bound, and why practice uses computational security.
9
What are substitution and permutation in the context of encryption algorithms?
KnownRevise
Substitution replaces each symbol or block of bits with another according to a key-dependent rule or a fixed table, called an S-box. It provides confusion: the relationship between the key and the ciphertext becomes complex and nonlinear. Permutation (transposition) rearranges the positions of symbols or bits without changing their values. It provides diffusion: each plaintext bit influences many ciphertext bits, so local patterns spread out. Claude Shannon identified confusion and diffusion as the two properties a strong cipher needs. Classical ciphers used one or the other: the Caesar cipher substitutes, rail-fence ciphers transpose, and each alone is easy to break. Modern block ciphers combine both over many rounds with round keys, either as a substitution-permutation network (SPN), like AES, or inside a Feistel structure, like DES.
Read full answerHide full answer
Applies toblock cipher design (Python 3.12 toy example)
Code Example: A Toy Substitution-Permutation Network
# A toy 16-bit substitution-permutation network (4 rounds). For illustration only.
SBOX = [0xE, 0x4, 0xD, 0x1, 0x2, 0xF, 0xB, 0x8, 0x3, 0xA, 0x6, 0xC, 0x5, 0x9, 0x0, 0x7]
INV_SBOX = [SBOX.index(i) for i in range(16)]
PERM = [0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15] # bit i moves to PERM[i]
def substitute(x, box):
# Confusion: replace each 4-bit nibble through a nonlinear table
return sum(box[(x >> (4 * i)) & 0xF] << (4 * i) for i in range(4))
def permute(x):
# Diffusion: move bits so each nibble feeds several S-boxes next round
return sum(((x >> i) & 1) << PERM[i] for i in range(16))
def encrypt(block, round_keys):
for k in round_keys[:-1]:
block = permute(substitute(block ^ k, SBOX))
return block ^ round_keys[-1]
def decrypt(block, round_keys):
block ^= round_keys[-1]
for k in reversed(round_keys[:-1]):
block = substitute(permute(block), INV_SBOX) ^ k # PERM is its own inverse
return block
keys = [0x3A94, 0xD63F, 0x1C2B, 0x8E07, 0x5B61]
c1 = encrypt(0x1234, keys)
c2 = encrypt(0x1235, keys) # flip one plaintext bit
print(hex(c1), hex(c2), bin(c1 ^ c2).count("1"), "bits differ") # 0x85d5 0x11f 6 bits differ
print(hex(decrypt(c1, keys))) # 0x1234
The 4-bit S-box (the one used in Heys’s well-known SPN tutorial) is nonlinear, and the bit permutation sends each output bit of an S-box to a different S-box in the next round. After a few rounds, flipping one plaintext bit changes many ciphertext bits. A real cipher uses many more rounds, larger blocks and a proper key schedule. This toy cipher is not secure.
Comparison
Substitution
Permutation
Operation
Replace values (S-boxes, lookup tables)
Rearrange positions (P-boxes, bit shuffles, row shifts)
Shannon property
Confusion
Diffusion
Linear?
Nonlinear (essential for security)
Linear
Alone
Breakable by frequency analysis (simple substitution)
Because each technique alone leaves statistical patterns (letter frequencies, or the letters themselves), they are easy to break. Combining them repeatedly with key material removes those patterns.
Why Both Are Needed
Substitution without diffusion: each S-box works on a small piece, so an attacker can attack pieces separately.
Diffusion without substitution: the whole cipher stays linear, so a system of linear equations reveals the key.
Together, over rounds: nonlinearity spreads across the whole block. This defeats linear and differential cryptanalysis when the S-boxes and the number of rounds are well chosen.
Good S-Box Properties
Property
Purpose
High nonlinearity
Resists linear cryptanalysis
Low differential uniformity
Resists differential cryptanalysis
Bijective (for SPNs)
Allows decryption
No fixed points or simple algebraic structure
Avoids algebraic attacks
The AES S-box is built from multiplicative inversion in GF(2⁸) followed by an affine transformation, which gives excellent values for these properties.
Pitfalls
Designing your own S-boxes or ciphers for real systems: use AES or ChaCha20.
Table-lookup implementations of S-boxes can leak keys through cache-timing side channels; use hardware instructions (AES-NI) or constant-time code.
Too few rounds: most attacks on reduced-round versions exploit insufficient diffusion.
Interview Tips
Map substitution → confusion and permutation → diffusion (Shannon).
Explain why each alone is weak and how rounds combine them.
Give AES (SubBytes, ShiftRows, MixColumns) and DES S-boxes as examples.
10
Explain the basic principle behind the AES encryption algorithm.
KnownRevise
AES (Advanced Encryption Standard, the Rijndael cipher, standardised by NIST in FIPS 197 in 2001) is a symmetric block cipher that encrypts 128-bit blocks with a 128-, 192- or 256-bit key. It is a substitution-permutation network. The block is arranged as a 4×4 matrix of bytes (the state) and transformed over 10, 12 or 14 rounds (for 128-, 192- and 256-bit keys). Each round applies four steps: - SubBytes: a nonlinear S-box replaces every byte, providing confusion. - ShiftRows: each row is rotated left by its row index, spreading bytes across columns. - MixColumns: each column is multiplied by a fixed matrix over GF(2⁸), mixing its bytes. ShiftRows and MixColumns provide diffusion. - AddRoundKey: the state is XORed with a round key derived from the main key by the key schedule.
An initial AddRoundKey comes before the first round, and the final round omits MixColumns. Decryption applies the inverse steps in reverse. AES itself encrypts only one block, so in practice it is used in a mode of operation, preferably an authenticated mode such as GCM.
Read full answerHide full answer
Applies toAES (FIPS 197) and its modes (SP 800-38 series)
Structure
plaintext block (16 bytes) -> state (4x4 bytes)
AddRoundKey(K0)
repeat for rounds 1 .. Nr-1:
SubBytes -> ShiftRows -> MixColumns -> AddRoundKey(Ki)
final round Nr:
SubBytes -> ShiftRows -> AddRoundKey(KNr) (no MixColumns)
-> ciphertext block
Key size
Rounds
Security level
128 bits
10
128 bits
192 bits
12
192 bits
256 bits
14
256 bits (about 128 against Grover’s quantum search)
The Four Steps
Step
What it does
Purpose
SubBytes
Each byte → S-box(byte): inversion in GF(2⁸) plus an affine map
Nonlinearity (confusion)
ShiftRows
Row r rotated left by r bytes
Moves bytes between columns (diffusion)
MixColumns
Each column multiplied by a fixed MDS matrix over GF(2⁸)
Every input byte affects all four output bytes of the column
AddRoundKey
State XOR round key
Introduces the key
After two rounds, every output byte depends on every input byte. This full diffusion is why the round structure resists linear and differential cryptanalysis.
The OpenSSL enc command does not support GCM authentication tags, which is one reason applications use libraries with AEAD interfaces, such as libsodium, Go’s crypto/cipher, Java’s Cipher("AES/GCM/NoPadding") or Python’s cryptography package, rather than command-line tools.
Security and Performance
No practical attack breaks full AES; the best known attacks give only marginal improvements over brute force.
Hardware support (AES-NI on x86, the ARMv8 cryptography extensions) gives very high speed and constant-time execution.
Software table-based implementations can leak keys through cache-timing attacks.
Pitfalls
ECB mode, which leaks patterns (the famous “ECB penguin” image).
Reusing GCM nonces with the same key, which allows forgeries and plaintext recovery.
Unauthenticated CBC, which allows padding-oracle attacks.
Deriving keys from passwords with a plain hash: use a KDF such as Argon2id or PBKDF2.
Interview Tips
State the parameters: 128-bit block; 128/192/256-bit keys; 10/12/14 rounds.
Name the four steps and their roles: SubBytes, ShiftRows, MixColumns, AddRoundKey.
Stress modes of operation: use GCM, never ECB.
11
What is DES, and why is it considered insecure today?
KnownRevise
The Data Encryption Standard (DES) is a symmetric block cipher standardised by the US government in 1977 (FIPS 46), based on IBM’s Lucifer design, with input from the NSA. It encrypts 64-bit blocks using a 56-bit key: the key is 64 bits, but 8 of them are parity bits. It runs 16 rounds of a Feistel network with eight S-boxes. DES was the dominant cipher for two decades, and its design held up remarkably well against cryptanalysis. Its fatal weakness is the 56-bit key: only about 7.2 × 10¹⁶ possible keys, which is small enough to brute-force. In 1998 the EFF’s “Deep Crack” machine found a DES key in 56 hours, and in 1999 it worked with distributed.net to do it in 22 hours. Today the work is cheap on rented GPUs or FPGAs. Its 64-bit block is another problem: after about 2³² blocks (32 GB) under one key, birthday collisions leak information (the Sweet32 attack). DES was withdrawn in 2005 and replaced by AES. Triple DES was an interim fix and is now deprecated too.
Expansion (32 → 48 bits), XOR with the round key, 8 S-boxes (6 → 4 bits each), permutation
Standardised
1977 (FIPS 46); withdrawn 2005
Why It Is Insecure
Weakness
Explanation
Consequence
56-bit key
2⁵⁶ ≈ 7.2 × 10¹⁶ keys
Brute force in hours or less with dedicated or cloud hardware
64-bit block
Birthday bound at about 2³² blocks
Sweet32: plaintext recovery from long sessions using DES or 3DES
Weak and semi-weak keys
A few keys where encryption equals decryption, or pairs that undo each other
Minor, but awkward
Theoretical attacks
Differential (2⁴⁷ chosen plaintexts) and linear (2⁴³ known plaintexts) cryptanalysis
Not practical, but faster than brute force
Brute-Force History
Year
Effort
Time
1997
DESCHALL distributed project
About 96 days
1998
EFF Deep Crack (about $250,000 of custom hardware)
56 hours
1999
Deep Crack + distributed.net
22 hours 15 minutes
Later
FPGA clusters (COPACOBANA, 2006) and cloud services
About a day or much less, for little money
Interesting Design Facts
The S-boxes were secretly strengthened against differential cryptanalysis, which IBM and the NSA knew about years before it was published (1990).
The short key length was a political compromise, and was criticised from the start.
What Replaced It
Cipher
Status
DES
Insecure; withdrawn
3DES (TDEA)
Deprecated; NIST disallows it for encryption after 2023
AES (2001)
Current standard: 128-bit block, 128/192/256-bit keys
ChaCha20
Modern alternative stream cipher, fast in software
Pitfalls
Legacy systems (payment terminals, mainframes, old VPNs) still using DES or 3DES: plan migrations.
TLS configurations that still allow 3DES cipher suites (Sweet32).
“Fixing” DES by double encryption: 2DES adds almost nothing because of meet-in-the-middle attacks.
Interview Tips
Give the specs: 64-bit block, 56-bit key, 16 Feistel rounds.
Explain the main problem: a 56-bit key broken by brute force (Deep Crack 1998), plus 64-bit block birthday issues.
Mention the replacement by AES and that 3DES is deprecated.
12
Describe the differences between RSA and ECC (Elliptic Curve Cryptography).
KnownRevise
Both are public-key systems used for key exchange, encryption and digital signatures, but they rest on different hard problems. RSA relies on the difficulty of factoring the product of two large primes. ECC relies on the elliptic-curve discrete logarithm problem: given points P and Q = kP on a curve, finding k is hard. Because the best attacks on ECC are much weaker than those on factoring, ECC achieves the same security with far smaller keys: a 256-bit curve ≈ 3072-bit RSA (128-bit security). That makes ECC faster for key generation and signing, with smaller keys, signatures and certificates, which suits mobile and IoT devices and TLS. RSA’s advantages are very fast signature verification with small exponents, long history and universal support, and simpler mathematics. Modern protocols prefer ECC: X25519 for key exchange and Ed25519 or ECDSA P-256 for signatures. Both RSA and ECC are broken by large quantum computers (Shor’s algorithm), which is driving migration to post-quantum algorithms such as ML-KEM and ML-DSA.
TLS 1.3 key exchange, WebAuthn and passkeys, Signal, SSH, cryptocurrencies
Quantum vulnerability
Broken by Shor’s algorithm
Broken by Shor’s algorithm (with fewer qubits than RSA, by most estimates)
Example: Generating Keys
# RSA 3072-bit
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out rsa.key
# ECC: NIST P-256 and Ed25519
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out p256.key
openssl genpkey -algorithm ed25519 -out ed25519.key
ls -l rsa.key p256.key ed25519.key # the RSA key file is much larger
ssh-keygen -t ed25519 -C "dev@example.com" # modern SSH default choice
Common Curves
Curve
Use
Notes
P-256 (secp256r1)
ECDSA and ECDH in TLS, WebAuthn
NIST standard, widely supported, FIPS-approved
P-384
Higher-assurance government use
CNSA suite (being replaced by post-quantum algorithms)
Curve25519 (X25519, Ed25519)
Key exchange and signatures
Designed for safe, fast, constant-time implementations
secp256k1
Bitcoin, Ethereum
Used by cryptocurrencies
Choosing Today
Need
Recommendation
Key exchange
X25519 (with a post-quantum hybrid such as X25519MLKEM768 where supported)
Signatures
Ed25519, or ECDSA P-256 for FIPS or compatibility
Compatibility with old systems
RSA 2048 minimum, 3072+ for long-lived keys
Long-term confidentiality against future quantum computers
Hybrid post-quantum key exchange
Pitfalls
RSA below 2048 bits, or RSA with PKCS#1 v1.5 encryption padding (Bleichenbacher-style attacks).
ECDSA with weak or repeated nonces, which leaks the private key.
Unvalidated curve points in ECDH, which allows invalid-curve attacks.
Assuming either is quantum-safe.
Interview Tips
Contrast the hard problems, and give the key-size equivalence (256 versus 3072).
Compare performance and sizes, and typical uses.
Mention X25519 and Ed25519, and the quantum threat to both.
13
How does a stream cipher differ from a block cipher?
KnownRevise
A block cipher encrypts fixed-size blocks (128 bits for AES) as a unit: a keyed permutation turns each plaintext block into a ciphertext block. To encrypt longer messages it needs a mode of operation (GCM, CBC, CTR), and some modes need padding. A stream cipher generates a pseudorandom keystream from a key and a nonce, and encrypts by XORing the keystream with the plaintext bit by bit or byte by byte. It needs no padding, has low latency, and ciphertext is the same length as the plaintext. Modern stream ciphers such as ChaCha20 are fast in software. The line is blurry in practice: a block cipher in CTR mode (and GCM) works as a stream cipher, encrypting counters to make a keystream. Both kinds need authentication (AEAD: AES-GCM or ChaCha20-Poly1305), and stream-style encryption is catastrophically broken by nonce reuse.
Read full answerHide full answer
Applies toAES modes (SP 800-38A/D) and ChaCha20-Poly1305 (RFC 8439)
Comparison
Aspect
Block cipher
Stream cipher
Unit of encryption
Fixed blocks (64 or 128 bits)
Bits or bytes, via keystream XOR
Core primitive
Keyed permutation on a block
Keystream generator (pseudorandom function of key and nonce)
Padding
Needed in ECB and CBC modes
Never
Error propagation
Depends on mode (CBC: one block garbled plus one bit flipped in the next)
A flipped ciphertext bit flips one plaintext bit (malleable)
Nonce or IV
Mode-dependent (CBC needs random IVs; CTR and GCM need unique nonces)
Always needs a unique nonce
Reuse risk
ECB leaks patterns; CTR/GCM nonce reuse is catastrophic
Nonce reuse reveals plaintext XOR
Hardware speed
Very fast with AES-NI
ChaCha20 is fast on CPUs without AES instructions
Examples
AES, 3DES (legacy), Camellia
ChaCha20, Salsa20; RC4 (broken)
Authenticated forms
AES-GCM, AES-CCM, AES-GCM-SIV
ChaCha20-Poly1305, XChaCha20-Poly1305
How Each Works
Block cipher (CBC mode):
C1 = E_K(P1 XOR IV) C2 = E_K(P2 XOR C1) ... (padding on the last block)
Stream cipher / CTR mode:
keystream = E_K(nonce || 0) || E_K(nonce || 1) || ... (or ChaCha20(K, nonce, counter))
C = P XOR keystream (any length, no padding)
Which to Use
Situation
Choice
General data and network encryption on modern servers
AES-256-GCM
Devices without AES hardware (older phones, embedded)
ChaCha20-Poly1305
Random nonces for very many messages
XChaCha20-Poly1305 (192-bit nonces) or AES-GCM-SIV
Disk sectors (length-preserving)
AES-XTS
Legacy
Avoid RC4, DES and 3DES, and unauthenticated CBC
TLS 1.3 offers both kinds as AEADs: TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384 and TLS_CHACHA20_POLY1305_SHA256.
Security Notes
Malleability: with any XOR-based encryption, an attacker can flip chosen plaintext bits by flipping ciphertext bits. Only authentication stops this.
RC4 had biased keystream bytes and was banned from TLS in 2015 (RFC 7465).
Contrast fixed blocks plus modes with keystream XOR.
Note that CTR and GCM turn block ciphers into stream ciphers.
Stress unique nonces and AEAD (AES-GCM, ChaCha20-Poly1305).
14
Describe the Feistel cipher structure.
KnownRevise
A Feistel network (Horst Feistel, IBM, 1970s) builds a block cipher by splitting the block into two halves, L and R, and running several rounds. In each round: - L′ = R; - R′ = L ⊕ F(R, Kᵢ), where F is a keyed round function and Kᵢ is that round’s subkey.
After the last round the halves are swapped (or the final swap is omitted). Its key property is that decryption uses the same structure with the round keys in reverse order, and F does not need to be invertible: it can be any complex, nonlinear function. That makes hardware and software implementations compact. Security depends on the strength of F, the number of rounds and the key schedule. Luby and Rackoff proved that three or four rounds with a pseudorandom F already give a pseudorandom permutation; real ciphers use many more. DES (16 rounds), 3DES, Blowfish, Twofish, Camellia and others use Feistel structures. AES does not: it is a substitution-permutation network.
Read full answerHide full answer
Applies toblock cipher design (Python 3.12 toy example)
Code Example: A Toy 64-Bit Feistel Cipher
import hashlib
def round_function(half, key):
# F does not need to be invertible: any keyed pseudorandom function works
return int.from_bytes(hashlib.sha256(key + half.to_bytes(4, "big")).digest()[:4], "big")
def feistel(block, keys):
left, right = block >> 32, block & 0xFFFFFFFF
for k in keys:
left, right = right, left ^ round_function(right, k)
return (right << 32) | left # final swap, so decryption is the same circuit
keys = [bytes([i]) * 8 for i in range(1, 9)] # 8 toy round keys
plaintext = 0x0123456789ABCDEF
ciphertext = feistel(plaintext, keys)
print(hex(ciphertext)) # 0x5c2f18c4ba44b320
print(hex(feistel(ciphertext, list(reversed(keys))))) # 0x123456789abcdef: same code, keys reversed
The round function is SHA-256-based and not invertible, yet decryption works by running the same feistel function with the keys reversed. This toy is for illustration; it is not a vetted cipher.
One Round
L_i R_i
| |-------+
| | v
| | F(R_i, K_i)
v | |
XOR <-------------------------+
| |
+------- swap -----+
v v
L_{i+1} = R_i R_{i+1} = L_i XOR F(R_i, K_i)
Why Decryption Works
Given L′ = R and R′ = L ⊕ F(R, K), the inverse is R = L′ and L = R′ ⊕ F(L′, K). That is the same operation with the halves swapped. So only F’s output is needed, never its inverse.
Unbalanced Feistel networks: the halves have different sizes (used in some hash functions and format-preserving encryption).
Format-preserving encryption (NIST FF1 and FF3-1) uses Feistel networks to encrypt values such as card numbers while keeping their format.
Lai-Massey structures (IDEA) are a related design.
Pitfalls
Too few rounds: with only two rounds, the structure leaks relationships between inputs and outputs directly.
Weak round functions (linear F), which make the whole cipher linear.
Poor key schedules, which allow slide or related-key attacks.
Interview Tips
Write the round equations: L′ = R, R′ = L ⊕ F(R, K).
Stress that decryption is the same structure with reversed keys and F need not be invertible.
Name DES as the classic example, and contrast with AES’s SPN.
15
What are the key differences between DES and 3DES?
KnownRevise
3DES (Triple DES, officially TDEA) was created to fix DES’s 56-bit key without designing a new cipher. It applies DES three times per block, usually as Encrypt–Decrypt–Encrypt (EDE) with keys K1, K2, K3: C = E_K3(D_K2(E_K1(P))). With three independent keys (168 bits of key material), meet-in-the-middle attacks reduce the effective strength to about 112 bits. Two-key 3DES (K1 = K3) gives about 80 bits against known attacks. The EDE order provides backward compatibility: with K1 = K2 = K3 it equals single DES. 3DES is much stronger than DES against brute force, but it is three times slower. It keeps DES’s 64-bit block, so it is vulnerable to birthday attacks on long sessions (Sweet32, 2016). NIST deprecated 3DES and disallowed it for encryption after 2023. Both should be replaced by AES.
Read full answerHide full answer
Applies toDES (FIPS 46-3) and TDEA (NIST SP 800-67)
Comparison
Aspect
DES
3DES (TDEA)
Structure
16-round Feistel
Three DES passes (48 rounds), EDE
Key length
56 bits
168 bits (three keys) or 112 bits (two keys)
Effective security
56 bits (brute-forced in 1998)
About 112 bits (three keys); about 80 bits (two keys)
Block size
64 bits
64 bits (unchanged)
Speed
Baseline
About 3 times slower
Backward compatibility
—
With K1 = K2 = K3, equals DES
Status
Withdrawn 2005
Deprecated; disallowed for encryption after 2023 (NIST SP 800-131A Rev. 2)
Known practical attacks
Brute force
Sweet32 (birthday attack on 64-bit blocks)
Why Three Passes, Not Two
2DES: C = E_K2(E_K1(P)) with 112 bits of key
Meet-in-the-middle: encrypt P under all 2^56 values of K1, decrypt C under all 2^56 values of K2,
match the middle values -> about 2^57 work (plus a lot of memory)
=> 2DES is barely stronger than DES, so 3DES uses three passes.
3DES with three keys still suffers from meet-in-the-middle, which is why its 168-bit key gives about 112-bit security.
The 64-Bit Block Problem (Sweet32)
With a 64-bit block, ciphertext block collisions become likely after about 2³² blocks (32 GB) under one key (the birthday bound). In CBC mode, a collision reveals the XOR of two plaintext blocks. Sweet32 showed attackers could recover HTTP cookies from long-lived HTTPS connections that used 3DES. NIST therefore limited 3DES to 2²⁰ blocks per key before it was disallowed.
Where 3DES Still Appears
Payment industry legacy (PIN blocks, older EMV keys), which is migrating to AES under PCI rules.
Old VPNs, mainframes and embedded devices.
Legacy TLS cipher suites: they should be disabled.
Assuming 168-bit 3DES has 168-bit security: it is about 112 bits.
Using two-key 3DES for new systems.
Long sessions with 64-bit block ciphers.
Interview Tips
Explain EDE with three keys, and the backward compatibility with DES.
Give effective security (112 bits, because of meet-in-the-middle) and why not 2DES.
Mention the 64-bit block (Sweet32) and deprecation in favour of AES.
16
Explain the main security features of the RSA algorithm.
KnownRevise
RSA’s security rests on the difficulty of factoring a large modulus n = p·q (the RSA problem: computing e-th roots modulo n without knowing the factors). Key generation: - pick two large random primes p and q; - compute n = pq and φ(n) = (p − 1)(q − 1); - choose a public exponent e (usually 65537) coprime to φ(n); - compute the private exponent d = e⁻¹ mod φ(n).
Encryption is c = mᵉ mod n; decryption is m = cᵈ mod n. Signing is s = hᵈ mod n; verification checks sᵉ mod n = h. Its practical security depends on several features beyond the mathematics: - sufficient key size: 2048 bits minimum, 3072 or more for long-term use; - randomised padding: OAEP for encryption, PSS for signatures. Textbook RSA is deterministic and malleable; - high-quality random primes; - protection of the private key, including against side channels.
Read full answerHide full answer
RSA is broken by Shor’s algorithm on a large quantum computer, so it is being phased out in favour of post-quantum algorithms for long-term security.
Applies to: RSA (PKCS #1 v2.2, RFC 8017) (Python 3.12 toy example)
Code Example: The Arithmetic With Tiny Numbers
from math import gcd
# Toy RSA with tiny primes, to show the arithmetic. Real keys use 2048+ bit primes and OAEP/PSS padding.
p, q = 61, 53
n = p * q # 3233, public modulus
phi = (p - 1) * (q - 1) # 3120
e = 17 # public exponent (65537 in practice)
assert gcd(e, phi) == 1
d = pow(e, -1, phi) # 2753, private exponent: e*d = 1 mod phi
print(n, e, d) # 3233 17 2753
m = 65
c = pow(m, e, n) # encrypt with the public key
print(c, pow(c, d, n)) # 2790 65: decrypting with the private key restores m
h = 123 # stands in for a padded hash of a message
s = pow(h, d, n) # sign with the private key
print(s, pow(s, e, n) == h) # 2746 True: verify with the public key
# Textbook RSA is malleable: multiplying ciphertexts multiplies plaintexts
c2 = pow(2, e, n)
print(pow(c * c2 % n, d, n)) # 130 = 65 * 2, which is why real RSA needs randomised padding
The numbers are tiny so the steps are visible; anyone can factor 3233. The last line shows malleability: textbook RSA lets an attacker transform ciphertexts in predictable ways. Real RSA therefore always uses padding (OAEP or PSS), and real code should use a vetted library, never hand-written RSA.
Security Features and Requirements
Feature
Why it matters
Hardness of factoring
The best classical algorithm (the general number field sieve) is sub-exponential, so large keys stay out of reach
Key size
2048 bits ≈ 112-bit security; 3072 ≈ 128-bit; RSA-250 (829 bits) was factored in 2020
OAEP padding (encryption)
Randomised and provably secure in the random-oracle model; prevents malleability and dictionary attacks
PSS padding (signatures)
Randomised and provably secure; PKCS#1 v1.5 signatures are still acceptable but PSS is preferred
Public exponent e = 65537
Fast verification; small values such as e = 3 are risky with weak padding
Good prime generation
Weak randomness has produced keys sharing primes (found by computing GCDs across many public keys) and the ROCA flaw (2017) in a smart-card library
Private key protection
HSMs, constant-time code, blinding against timing attacks
CRT optimisation with fault checks
A single computational fault during CRT signing can reveal the factors (Bellcore attack); verify signatures before releasing them
Known Attacks on Misused RSA
Attack
Cause
Prevention
Bleichenbacher (1998), ROBOT (2017)
PKCS#1 v1.5 encryption padding oracles
OAEP, or no RSA key transport (TLS 1.3 removed it)
Small-exponent / Håstad broadcast
Same message to several recipients with e = 3 and no padding
Proper padding
Common-modulus attack
Same n with different e values
Unique n per key
Shared primes
Poor randomness during key generation
A good CSPRNG
Timing and power side channels
Exponentiation time depends on d
Constant-time code, blinding
Fault attacks on CRT
Hardware glitches
Verify the result before output
Where RSA Is Used Today
TLS certificates and signatures (many sites now use ECDSA instead).
Code signing, S/MIME, document signing.
Key wrapping in some enterprise systems and HSMs.
TLS 1.3 removed RSA key transport: RSA is used there only for signatures, with ephemeral ECDHE for forward secrecy.
Pitfalls
Textbook RSA or homemade implementations.
1024-bit keys, which are considered breakable by well-resourced attackers.
PKCS#1 v1.5 encryption in new designs.
Reusing one key for both encryption and signatures.
Interview Tips
Explain n = pq, e, d, and modular exponentiation, with security from factoring.
Stress padding (OAEP and PSS), key size and randomness.
Mention side channels, Bleichenbacher attacks and the quantum threat.
17
What is quantum cryptography, and how might it impact current encryption methods?
KnownRevise
Two different ideas are often mixed up: - Quantum cryptography in the strict sense means using quantum physics to protect information. Its main application is quantum key distribution (QKD), such as the BB84 protocol (1984). Two parties exchange photons in random bases, and because measuring a quantum state disturbs it, any eavesdropping shows up as errors. They then derive a shared secret key. - Quantum computing is the threat to today’s encryption. Shor’s algorithm on a large, error-corrected quantum computer would break RSA, Diffie-Hellman and elliptic-curve cryptography completely, which covers most key exchange and signatures today. Grover’s algorithm gives only a square-root speed-up for brute force, so AES-256 and SHA-384/512 remain safe; AES-128 drops to about 64-bit quantum security, which is often judged still adequate, but 256-bit keys are preferred for margin.
The main response is not QKD but post-quantum cryptography (PQC): new classical algorithms believed to resist quantum attacks, standardised by NIST in 2024 as ML-KEM (FIPS 203), ML-DSA (FIPS 204) and SLH-DSA (FIPS 205). They are being deployed now, often as hybrids, because of “harvest now, decrypt later” attacks on recorded traffic.
1. Alice sends photons, each with a random bit encoded in a randomly chosen basis (+ or x).
2. Bob measures each photon in a randomly chosen basis.
3. Over a public (authenticated) channel they compare bases, not bits; they keep the matching ones.
4. They compare a sample of the kept bits: a high error rate means an eavesdropper measured photons.
5. Error correction and privacy amplification produce the final shared key.
QKD strengths
QKD limitations
Security based on physics, not computational assumptions
Needs special hardware, fibre or free-space links, limited distance (about 100 km without trusted relays)
Detects eavesdropping
Still needs an authenticated classical channel, so classical crypto is still required
Implementation attacks on hardware have been demonstrated; expensive; point-to-point
Agencies such as the NSA and the UK’s NCSC currently recommend post-quantum cryptography rather than QKD for most uses.
Post-Quantum Standards
Standard
Algorithm
Type
FIPS 203
ML-KEM (from CRYSTALS-Kyber)
Key encapsulation (lattice-based)
FIPS 204
ML-DSA (from CRYSTALS-Dilithium)
Signatures (lattice-based)
FIPS 205
SLH-DSA (from SPHINCS+)
Signatures (hash-based, conservative)
Planned
FN-DSA (Falcon), HQC
Compact signatures; a backup KEM based on codes
Major browsers and Cloudflare already use the hybrid X25519MLKEM768 key exchange in TLS 1.3. OpenSSH defaults to a hybrid post-quantum key exchange as well.
Why Act Before Quantum Computers Exist
Harvest now, decrypt later: adversaries can record encrypted traffic today and decrypt it once a large enough quantum computer exists. Data that must stay secret for 10 years or more is already at risk.
Migration takes years: inventories, protocols, hardware, certificates and partners all have to change.
Signatures matter later, but long-lived roots of trust (firmware signing, root CAs) need planning now.
Pitfalls
Confusing QKD with post-quantum cryptography.
Assuming AES is broken by quantum computers: it is not, with 256-bit keys.
Waiting for “Q-day” before starting an inventory of cryptography.
Rolling out post-quantum algorithms alone too early: hybrids protect against flaws in the new schemes.
Interview Tips
Distinguish QKD (quantum physics for key exchange) from quantum attacks (Shor and Grover).
Explain that RSA and ECC are broken; AES-256 and SHA-2 survive.
Name the NIST PQC standards, hybrid deployment and harvest-now-decrypt-later.
18
What is cryptanalysis?
KnownRevise
Cryptanalysis is the study of breaking cryptographic systems: recovering plaintexts or keys, forging messages or signatures, or showing that a scheme is weaker than claimed, without being given the secret key. Together with cryptography (designing systems), it forms cryptology. Cryptanalysis is how algorithms earn trust: AES, SHA-3 and the post-quantum standards were chosen after years of public cryptanalysis, while MD5, SHA-1, DES and RC4 were retired because of it. Attacks are classified by: - what the attacker can access: ciphertext only, known plaintext, chosen plaintext, chosen ciphertext; - the technique: brute force, frequency analysis, differential and linear cryptanalysis, algebraic attacks, birthday and meet-in-the-middle attacks, side channels, implementation and protocol attacks; - the goal: total break (the key), plaintext recovery, distinguishing, or forgery.
In practice, most real-world breaks come from implementation and usage mistakes (bad randomness, nonce reuse, padding oracles, timing leaks), not from breaking the mathematics.
Read full answerHide full answer
Applies tocryptanalysis of classical and modern schemes
Attack Models (Attacker Capabilities)
Model
Attacker has
Example
Ciphertext-only
Only ciphertexts
Frequency analysis of classical ciphers
Known-plaintext
Some plaintext–ciphertext pairs
Enigma “cribs” at Bletchley Park; linear cryptanalysis of DES
Chosen-plaintext (CPA)
Can get chosen plaintexts encrypted
Differential cryptanalysis; attacks on deterministic encryption
Chosen-ciphertext (CCA)
Can get chosen ciphertexts decrypted (or learn whether decryption succeeds)
Padding-oracle attacks (Bleichenbacher on RSA, Vaudenay on CBC)
Related-key
Encryptions under keys with known relationships
Attacks on some key schedules (reduced AES-256 results)
Assume attackers target implementations: use vetted libraries, constant-time code and AEAD, and get reviews.
Pitfalls
Treating “unbroken so far” as proof.
Proprietary, secret algorithms: they get little public cryptanalysis and often fail once examined (for example, early GSM and DVD encryption).
Ignoring side channels in hardware or shared cloud environments.
Interview Tips
Define it as breaking crypto without the key, and its role in building trust.
List the attack models (ciphertext-only to chosen-ciphertext) and the main techniques.
Stress that implementation flaws are the most common real-world breaks.
19
What is a brute force attack, and how can systems be protected against it?
KnownRevise
A brute force attack tries every possible key, password or value until one works. It always succeeds eventually, so defence is about making the search too large or too slow to finish in useful time. Variants include: - exhaustive key search against ciphers; - offline password cracking against stolen hashes, using GPUs, dictionaries, rules and leaked password lists; - online guessing against login forms and APIs; - credential stuffing, which reuses passwords leaked from other sites; - password spraying: a few common passwords tried against many accounts.
Protection depends on the target: - Keys: use large keys, 128 bits or more (2¹²⁸ is out of reach). - Stored passwords: use slow, salted, memory-hard hashing (Argon2id, scrypt, bcrypt). - Online logins: apply rate limiting, progressive delays, smart lockouts, CAPTCHAs and bot detection, plus multi-factor authentication and phishing-resistant passkeys. - Users:block breached and common passwords, and monitor for attacks.
Read full answerHide full answer
Applies tokey search and password attacks (Python 3.12 example)
Code Example: Why Slow Password Hashing Matters
import hashlib
import time
salt = b"per-user-random-salt"
pin = b"7391"
fast = hashlib.sha256(salt + pin).hexdigest() # one fast hash
slow = hashlib.pbkdf2_hmac("sha256", pin, salt, 100_000).hex() # deliberately slow
def crack(target, hash_fn):
for i in range(10_000): # every 4-digit PIN
guess = f"{i:04d}".encode()
if hash_fn(guess) == target:
return guess
return None
t = time.perf_counter()
print(crack(fast, lambda g: hashlib.sha256(salt + g).hexdigest())) # b'7391'
fast_time = time.perf_counter() - t
t = time.perf_counter()
slow_one = hashlib.pbkdf2_hmac("sha256", b"0000", salt, 100_000) # cost of ONE slow guess
slow_time = (time.perf_counter() - t) * 10_000 # estimate for all PINs
print(f"fast hash: all PINs in {fast_time:.3f}s; slow KDF: about {slow_time:.0f}s")
print(f"slowdown factor about {slow_time / fast_time:,.0f}x") # tens of thousands of times; varies by machine
A 4-digit PIN has only 10,000 possibilities, so a fast hash falls instantly. PBKDF2 with 100,000 iterations makes each guess tens of thousands of times more expensive (exact timings vary by machine). For real password storage, prefer Argon2id, which is also memory-hard, making GPU and ASIC attacks costly. Note that no hashing can save a tiny search space like a 4-digit PIN; that needs online limits or hardware-backed checks.
Search Space Matters
Secret
Possibilities
Fast offline attack (about 10¹¹ guesses per second)
4-digit PIN
10⁴
Instant
8 lowercase letters
About 2 × 10¹¹
Seconds
8 characters, all 95 printable
About 6.6 × 10¹⁵
About 18 hours
12 random characters, all 95 printable
About 5.4 × 10²³
About 170,000 years
5-word random passphrase (7,776-word list)
About 2.8 × 10¹⁹
Years, and much longer with slow hashing
128-bit key
About 3.4 × 10³⁸
Far beyond any feasible computation
Human-chosen passwords are far weaker than these numbers suggest, because attackers try common patterns first.
Defences
Layer
Defence
Cryptographic keys
128-bit or larger keys from a CSPRNG; AES-256 for long-term margin
Password storage
Argon2id (or scrypt, bcrypt, PBKDF2 for FIPS) with unique salts; optional pepper kept in an HSM or secret store
Online login
Rate limits per account and per IP, exponential backoff, temporary lockouts (avoid easy denial of service), CAPTCHAs after failures
Credential stuffing
Breached-password checks (for example the Have I Been Pwned k-anonymity API), bot detection, device fingerprinting
Authentication strength
MFA; passkeys (WebAuthn) remove passwords as a target
Password policy
NIST SP 800-63B: length over complexity rules, allow long passphrases, block known-bad passwords, no forced periodic changes
Monitoring
Alert on failed-login spikes, spraying patterns, impossible travel
API tokens
Long random tokens (128+ bits); constant-time comparison
Pitfalls
Fast hashes (MD5, SHA-256) for passwords, even with salt.
Lockouts per account only: password spraying bypasses them; combine with per-IP and global signals.
Short numeric codes (OTPs, reset codes) without strict attempt limits and expiry.
Revealing whether the username exists, which helps attackers focus.
Interview Tips
Define brute force as trying all possibilities; defences make it infeasible or detectable.
Separate offline attacks (slow hashing, key size) from online attacks (rate limits, MFA).
Mention Argon2id, credential stuffing, spraying and passkeys.
20
Describe a man-in-the-middle attack and how it can be prevented.
KnownRevise
In a man-in-the-middle (MITM) attack, an attacker secretly sits between two parties who believe they are talking directly. The attacker relays, reads and possibly modifies their traffic, or impersonates one side to the other. Ways to get into the path include: - ARP spoofing on a LAN; - rogue Wi-Fi access points (“evil twins”); - DNS spoofing or poisoning; - BGP hijacking; - malicious proxies or compromised routers; - malware on the endpoint.
Interception becomes useless when communications are encrypted and the endpoints are authenticated. The key defences: - TLS with proper certificate validation, with HSTS (and preload) so connections cannot be downgraded to HTTP; - mutual TLS or signed requests between services; - verified host keys in SSH; - authenticated key exchange: unauthenticated Diffie-Hellman is itself vulnerable to MITM; - certificate pinning in some mobile apps, and Certificate Transparency monitoring; - DNSSEC and encrypted DNS; - network hygiene: 802.1X, dynamic ARP inspection, WPA3; - phishing-resistant authentication (passkeys, which are bound to the origin).
Read full answerHide full answer
Applies tonetwork and application security (TLS 1.3, SSH, Wi-Fi)
How It Works
Normal: Client <--------------------------------> Server
MITM: Client <---> Attacker <---> Server
the client thinks the attacker is the server; the server thinks the attacker is the client
If the client does not verify the server’s identity, the attacker can complete separate encrypted sessions with each side and decrypt everything in between.
Why Authentication Is Essential: Unauthenticated Diffie-Hellman
Alice --g^a--> Mallory --g^m--> Bob
Alice <--g^m-- Mallory <--g^b-- Bob
Alice shares key K1 = g^am with Mallory; Bob shares K2 = g^bm with Mallory.
Mallory decrypts with K1, re-encrypts with K2: neither side notices.
TLS prevents this because the server signs the handshake with a key bound to its name by a certificate, and the client validates it.
Attack Techniques and Defences
Technique
Defence
ARP spoofing on a LAN
Dynamic ARP inspection, port security, segmented networks, encrypted protocols
Rogue or evil-twin Wi-Fi
WPA3-Enterprise with server certificate validation, VPN on untrusted networks, TLS everywhere
DNS spoofing
DNSSEC validation, DNS over HTTPS or TLS, TLS certificate checks
SSL stripping (downgrade to HTTP)
HSTS with includeSubDomains and preload; redirect all HTTP to HTTPS
Fraudulent certificates
Certificate Transparency monitoring, CAA DNS records, pinning in controlled clients
TLS interception by proxies
Endpoint policies; pinning for sensitive apps; mutual TLS
BGP hijacking
RPKI route origin validation; TLS still protects content
After the first visit, the browser refuses to connect over plain HTTP for two years. With preload, the browser enforces it even on the first visit.
Developer Checklist
Never disable certificate verification (verify=False, InsecureSkipVerify: true, trust-all managers), even “temporarily”.
Validate the hostname, not just that the certificate chain is valid.
Use TLS 1.2 or 1.3 only, with modern cipher suites.
Use mTLS or a service mesh between internal services.
Use signed tokens with audience checks, so stolen tokens cannot be replayed elsewhere.
Pitfalls
Trust-all certificate code shipped to production.
Mixed content: an HTTPS page loading scripts over HTTP.
Ignoring certificate warnings and training users to click through them.
Unauthenticated encryption (“we use Diffie-Hellman, so we’re safe”).
Interview Tips
Define MITM as intercepting and relaying while impersonating both sides.
Explain that encryption without authentication does not stop it, using the DH example.
List defences: TLS validation, HSTS, mTLS, SSH host keys, DNSSEC, Certificate Transparency and passkeys.
21
Explain what a side-channel attack is.
KnownRevise
A side-channel attack extracts secrets not by breaking the algorithm’s mathematics but by observing physical or behavioural effects of an implementation: - how long an operation takes (timing); - how much power it draws, or what electromagnetic emissions it produces; - which cache lines or memory it touches; - sound, error messages, or response sizes.
If these depend on secret data, for example a branch on a key bit, an early exit in a comparison, or a table lookup indexed by key material, an attacker can collect measurements and recover the key statistically. Famous examples: - Kocher’s timing attacks on RSA and Diffie-Hellman (1996); - differential power analysis on smart cards (1999); - cache-timing attacks on table-based AES; - Spectre and Meltdown (2018), which leak data through speculative execution; - Hertzbleed (2022), which turns power differences into timing via CPU frequency scaling; - padding oracles, where error messages reveal information.
Read full answerHide full answer
Defences: constant-time code, hardware crypto instructions, blinding and masking, noise and shielding in hardware, uniform errors, and isolation between tenants.
Applies to: implementations of cryptography in software and hardware
Types of Side Channels
Channel
What leaks
Example
Timing
Execution time depends on secrets
Early-exit string comparison of MACs; RSA square-and-multiply timing
Cache
Memory access patterns
Flush+Reload and Prime+Probe against AES T-tables, often across VMs
Power
Current consumption per operation
Simple and differential power analysis on smart cards, IoT devices
Electromagnetic
EM emanations
Key extraction from nearby phones or laptops
Acoustic
Sounds from electronic components
RSA key extraction from laptop noise (2013 research)
Speculative execution
Microarchitectural state
Spectre, Meltdown, and later variants
Fault injection (an active relative)
Results computed with induced glitches
Bellcore attack on RSA-CRT
Error and length oracles
Different errors or sizes
Padding oracles; CRIME and BREACH (compression ratios)
Example: A Timing Leak and Its Fix
import hmac
def insecure_equals(a: bytes, b: bytes) -> bool:
if len(a) != len(b):
return False
for x, y in zip(a, b):
if x != y: # returns earlier when the first bytes differ:
return False # response time reveals how many leading bytes are correct
return True
def secure_equals(a: bytes, b: bytes) -> bool:
return hmac.compare_digest(a, b) # runs in time independent of where bytes differ
tag = bytes.fromhex("9f86d081884c7d65")
print(insecure_equals(tag, bytes.fromhex("9f86d081884c7d65"))) # True
print(secure_equals(tag, bytes.fromhex("9f86d00000000000"))) # False
An attacker who can measure response times precisely can guess a MAC one byte at a time against the insecure version.
Defences
Defence
Detail
Constant-time programming
No branches, loop bounds or memory addresses depending on secrets
Hardware instructions
AES-NI and ARMv8 crypto extensions avoid table lookups
Vetted libraries
libsodium, BoringSSL, Go’s crypto packages, Tink
Blinding (RSA)
Randomise inputs so timing is unrelated to the secret
Masking (hardware)
Split secrets into random shares in each operation
Hardware countermeasures
Shielding, noise, secure elements, HSMs
Uniform errors
Same response and timing for every decryption failure
Do not compress secrets together with attacker-controlled data (BREACH)
Fault checks
Verify signatures before releasing them; detect glitches
Pitfalls
Comparing MACs, tokens or password hashes with ==.
Assuming the network adds enough noise: remote timing attacks work with enough samples.
Custom crypto implementations with data-dependent branches.
Different error messages for “bad padding” and “bad MAC”.
Interview Tips
Define side channels as leakage from the implementation, not the mathematics.
Give examples: timing, cache, power, EM, Spectre and padding oracles.
Explain constant-time code with the comparison example, plus blinding, masking and isolation.
22
What is a chosen plaintext attack?
KnownRevise
In a chosen-plaintext attack (CPA), the attacker can choose plaintexts and obtain their encryptions under the target key. The attacker has an encryption oracle, but not the key. The goal is to learn something the encryption should hide: the key, the content of other ciphertexts, or even just which of two messages a ciphertext contains. The model is realistic: - anyone can encrypt with a public key; - an attacker can make a web app encrypt data they submit (cookies, tokens, form fields); - they can inject content into a TLS session alongside secrets (the BEAST and CRIME attacks).
Modern encryption must therefore be IND-CPA secure: even an attacker who chooses messages cannot tell which of two chosen messages was encrypted. A direct consequence is that encryption must be randomised (fresh IVs or nonces). Deterministic encryption, such as ECB mode or a fixed nonce, fails, because the attacker simply encrypts guesses and compares. An adaptive CPA lets the attacker choose later plaintexts based on earlier results.
Read full answerHide full answer
Applies tosecurity models for encryption (Python 3.12 toy example)
Code Example: A Deterministic Scheme Fails Under CPA
import hashlib
import hmac
import secrets
KEY = secrets.token_bytes(32)
def deterministic_encrypt(msg):
# BAD: same key and same (fixed) nonce for every message, so encryption is deterministic
stream = hashlib.sha256(KEY + b"fixed-nonce").digest()
return bytes(m ^ s for m, s in zip(msg, stream))
def randomized_encrypt(msg):
nonce = secrets.token_bytes(12)
stream = hashlib.sha256(KEY + nonce).digest()
return nonce + bytes(m ^ s for m, s in zip(msg, stream))
# The victim encrypts a vote; the attacker sees only the ciphertext...
observed = deterministic_encrypt(b"VOTE:NO ")
# ...but can get chosen plaintexts encrypted (an encryption oracle), so it tries each candidate
for guess in (b"VOTE:YES", b"VOTE:NO "):
if hmac.compare_digest(deterministic_encrypt(guess), observed):
print("deterministic scheme leaks the vote:", guess)
# With a fresh random nonce per message, encrypting the same plaintext gives a new ciphertext
observed = randomized_encrypt(b"VOTE:NO ")
print(any(randomized_encrypt(g) == observed for g in (b"VOTE:YES", b"VOTE:NO "))) # False
When the same plaintext always produces the same ciphertext, the attacker only needs the oracle to encrypt candidate messages (“YES” or “NO”) and compare. Randomised encryption with a fresh nonce gives a different ciphertext every time. This is a toy construction for illustration; use AES-GCM or ChaCha20-Poly1305 in practice.
Attack Models Compared
Model
Attacker capability
Security goal
Ciphertext-only
Sees ciphertexts
Basic secrecy
Known-plaintext
Knows some plaintext–ciphertext pairs
Key secrecy
Chosen-plaintext (CPA)
Encrypts messages of their choice
IND-CPA
Chosen-ciphertext (CCA, CCA2 adaptive)
Also decrypts chosen ciphertexts (except the target)
IND-CCA2: what AEAD and RSA-OAEP provide
The IND-CPA Game
1. The challenger generates a key.
2. The attacker may ask for encryptions of any messages.
3. The attacker submits two equal-length messages m0 and m1.
4. The challenger flips a coin b and returns c = Enc(m_b).
5. The attacker may keep querying encryptions, then guesses b.
Secure if no efficient attacker guesses b with probability noticeably better than 1/2.
A deterministic scheme loses immediately: the attacker queries Enc(m0) and compares it with c.
Real-World Chosen-Plaintext Attacks
Attack
Chosen plaintext
Weakness exploited
ECB “penguin” and cookie attacks
Attacker-controlled input next to secrets
Deterministic blocks
BEAST (2011)
JavaScript-injected requests
Predictable CBC IVs in TLS 1.0
CRIME and BREACH (2012–13)
Injected guesses near secret tokens
Compression before encryption changes ciphertext length
Public-key encryption
Anyone can encrypt
Textbook RSA is deterministic, so guesses can be confirmed; OAEP randomises
Differential cryptanalysis
Pairs of chosen plaintexts
Statistical weaknesses in a cipher
Defences
Randomised encryption: unique nonces or random IVs (AES-GCM, ChaCha20-Poly1305).
Never ECB, and never a fixed nonce.
Randomised padding for public-key encryption (OAEP), or KEM-based designs (HPKE, ML-KEM).
Avoid compressing secrets together with attacker-controlled data.
Aim higher: IND-CCA2 security via authenticated encryption, which covers CPA too.
Pitfalls
Deterministic encryption for searchable fields without understanding the leakage: equal values are visible.
Predictable IVs in CBC mode.
Length leaks: ciphertext size reveals information unless padded.
Interview Tips
Define CPA as attacker chooses plaintexts and sees their encryptions.
Explain IND-CPA and why it requires randomised encryption.
Give examples: ECB, BEAST, CRIME and BREACH, and textbook RSA.
23
How does a frequency analysis attack work against certain ciphers?
KnownRevise
Frequency analysis exploits the fact that natural languages use letters unevenly. In English, E is about 12–13% of letters, followed by T, A, O, I, N, and Q, X and Z are rare. Common pairs and words (TH, HE, THE, AND) repeat too. Monoalphabetic substitution ciphers, such as the Caesar cipher or a random letter substitution, replace each plaintext letter with the same ciphertext letter every time, so the ciphertext keeps the same frequency pattern, just relabelled. The attacker: 1. counts letter frequencies in the ciphertext; 2. matches them to the language’s known frequencies, so the most common ciphertext letter probably stands for E or T; 3. refines the guesses with digrams, trigrams, short words and context, until the text reads correctly.
The technique was first described by al-Kindi in the 9th century. Polyalphabetic ciphers (Vigenère) flatten frequencies, but fall once the key length is found (Kasiski examination or the index of coincidence), because each position is then a simple Caesar cipher. Modern ciphers are designed so the ciphertext looks uniformly random, which defeats frequency analysis entirely.
Read full answerHide full answer
Applies toclassical ciphers (Python 3.12 example)
Code Example: Breaking a Caesar Cipher
from collections import Counter
from string import ascii_uppercase as ABC
# Relative frequencies of letters in English text (percent)
ENGLISH = dict(zip(ABC, [8.2, 1.5, 2.8, 4.3, 12.7, 2.2, 2.0, 6.1, 7.0, 0.15, 0.77, 4.0, 2.4,
6.7, 7.5, 1.9, 0.095, 6.0, 6.3, 9.1, 2.8, 0.98, 2.4, 0.15, 2.0, 0.074]))
def shift(text, k):
return "".join(ABC[(ABC.index(c) + k) % 26] if c in ABC else c for c in text)
def chi_squared(text):
letters = [c for c in text if c in ABC]
counts = Counter(letters)
n = len(letters)
return sum((counts[c] - n * ENGLISH[c] / 100) ** 2 / (n * ENGLISH[c] / 100) for c in ABC)
plaintext = "MEET THE AGENT NEAR THE OLD TRAIN STATION AT SEVEN THIRTY TONIGHT"
ciphertext = shift(plaintext, 11)
print(ciphertext) # XPPE ESP LRPYE YPLC ESP ZWO ECLTY DELETZY LE DPGPY ESTCEJ EZYTRSE
# [('E', 12), ('P', 8), ('Y', 6)]: E is plaintext T and P is plaintext E. In short texts the top
# letter is not always E, so score every key instead of trusting the single most common letter.
print(Counter(c for c in ciphertext if c in ABC).most_common(3))
# Try every key; the decryption whose letter counts look most like English wins
best = min(range(26), key=lambda k: chi_squared(shift(ciphertext, -k)))
print(best, shift(ciphertext, -best)) # 11 MEET THE AGENT NEAR THE OLD TRAIN STATION ...
Rather than trusting the single most frequent letter, the code scores all 26 shifts with a chi-squared statistic against English letter frequencies, and picks the best fit. For a general substitution cipher (26! keys), attackers use the same scoring inside hill-climbing or simulated annealing searches over the key, plus digram statistics.
English Letter Frequencies (Approximate)
Letter
%
Letter
%
Letter
%
E
12.7
N
6.7
U
2.8
T
9.1
S
6.3
M
2.4
A
8.2
H
6.1
W
2.4
O
7.5
R
6.0
F
2.2
I
7.0
D
4.3
Q, J, X, Z
under 0.2 each
Which Ciphers Are Vulnerable
Cipher
Vulnerable?
Why
Caesar or shift cipher
Yes, trivially
One fixed relabelling; only 25 keys
Monoalphabetic substitution
Yes
Frequencies preserved
Homophonic substitution
Partly
Several symbols per common letter flatten single-letter counts, but digrams still leak
Vigenère (polyalphabetic)
Yes, after finding the key length
Each key position is a Caesar cipher
Playfair (digraphic)
Yes, with digram statistics
Pairs keep patterns
One-time pad
No
Uniform random key
AES, ChaCha20 (properly used)
No
Ciphertext is indistinguishable from random
AES in ECB mode
Partly, at block level
Repeated plaintext blocks give repeated ciphertext blocks
Breaking Vigenère: Finding the Key Length
Kasiski examination: repeated ciphertext fragments are often separated by multiples of the key length.
Index of coincidence: split the text into k columns; the right k gives columns whose letter statistics look like English (IC of about 0.066, versus about 0.038 for random text).
Then frequency-analyse each column as a separate Caesar cipher.
Modern Relevance
Deterministic encryption leaks frequencies too: if a database encrypts a “country” column deterministically, the most common ciphertext is probably the most common country. Attackers apply frequency analysis to encrypted databases and tokenised data.
Traffic analysis is a related idea: patterns of message sizes and timing reveal information even when the content is encrypted.
Pitfalls
Homemade “encryption” (XOR with a short repeating key, letter substitution) in applications: it is broken in seconds.
ECB mode or deterministic encryption on low-entropy data.
Short texts can mislead naive frequency analysis, which is why statistical scoring works better.
Interview Tips
Explain that substitution preserves frequencies, so map common ciphertext letters to E, T and A.
Mention digrams and words, and al-Kindi.
Contrast Vigenère (key length first) and modern ciphers (uniform output), and note deterministic encryption leakage.
24
What is the difference between HMAC and a simple hash function?
KnownRevise
A hash function such as SHA-256 takes only the data and produces a fingerprint. Anyone can compute it, so it detects accidental corruption, but it cannot prove authenticity: an attacker who changes the message simply recomputes the hash. HMAC (hash-based message authentication code, RFC 2104) mixes in a secret key:
HMAC(K, m) = H((K ⊕ opad) ‖ H((K ⊕ ipad) ‖ m))
Read full answerHide full answer
Only parties holding the key can produce or verify a valid tag, so HMAC provides integrity and authenticity between them. Its nested two-pass design also prevents the length-extension attack that breaks naive constructions such as H(key ‖ message) with SHA-256. HMAC does not provide non-repudiation, because both sides share the key; use digital signatures for that. Use a plain hash for checksums and content addressing, HMAC for API request signing, webhooks, cookies and tokens, and constant-time comparison when checking tags.
Applies to: HMAC (RFC 2104, FIPS 198-1) with SHA-2 (Python 3.12 example)
Code Example: Forging Against a Plain Hash Versus HMAC
import hashlib
import hmac
import secrets
key = secrets.token_bytes(32) # shared only by the sender and the receiver
message = b'{"to": "alice", "amount": 100}'
plain_hash = hashlib.sha256(message).hexdigest()
tag = hmac.new(key, message, hashlib.sha256).hexdigest()
# An attacker changes the message. With a plain hash they simply recompute it: no key is needed.
forged = b'{"to": "mallory", "amount": 100}'
forged_hash = hashlib.sha256(forged).hexdigest()
print("plain hash check passes for forgery:", hashlib.sha256(forged).hexdigest() == forged_hash) # True
# With HMAC, the attacker cannot produce a valid tag without the key
attacker_tag = hmac.new(secrets.token_bytes(32), forged, hashlib.sha256).hexdigest()
expected = hmac.new(key, forged, hashlib.sha256).hexdigest()
print("HMAC check passes for forgery:", hmac.compare_digest(attacker_tag, expected)) # False
print("HMAC check passes for original:",
hmac.compare_digest(tag, hmac.new(key, message, hashlib.sha256).hexdigest())) # True
The attacker can make a plain hash match any message they like. With HMAC, they cannot create the right tag without the secret key. Tags are compared with hmac.compare_digest, which avoids timing leaks.
Comparison
Aspect
Hash (SHA-256)
HMAC-SHA256
Inputs
Message
Secret key + message
Who can compute it
Anyone
Only key holders
Detects accidental changes
Yes
Yes
Detects malicious changes
Only if the hash itself is delivered over a trusted channel
Yes
Authenticates the sender
No
Yes (as “someone with the key”)
Non-repudiation
No
No (shared key)
Length-extension safe
Not applicable; but H(key ‖ msg) with SHA-2 is unsafe
Webhooks, API signing (AWS SigV4), JWT HS256, session cookies, HKDF
Why Not Just H(key ‖ message)?
SHA-256 and SHA-512 are Merkle–Damgård constructions: the digest is the internal state after processing the input. Given H(key ‖ m) and the length of the key, an attacker can compute H(key ‖ m ‖ padding ‖ extra) without knowing the key: a length-extension attack (it was used against Flickr’s API signatures in 2009). HMAC’s outer hash prevents this. SHA-3 and BLAKE2/3 are not vulnerable to length extension and offer keyed modes (KMAC, keyed BLAKE2), but HMAC remains the most widely supported choice.
Example: Verifying a Webhook
Sender: signature = hex(HMAC-SHA256(secret, timestamp + "." + raw_body))
headers: X-Signature: <signature>, X-Timestamp: <timestamp>
Receiver: recompute with the same secret over the RAW body bytes,
compare with a constant-time function,
reject if the timestamp is older than about 5 minutes (prevents replay).
Pitfalls
Using a plain hash as an integrity check for data an attacker can modify along with its hash.
== comparisons of tags, which leak timing.
Verifying a re-serialised body instead of the raw bytes received.
Short, guessable or shared keys across many clients; use random keys of 32 bytes per client.
No replay protection (timestamps or nonces).
Interview Tips
Contrast keyless hash (anyone can recompute) with keyed HMAC (only key holders).
Write the HMAC formula, and explain length-extension attacks on H(key ‖ m).
Mention constant-time comparison, and that signatures are needed for non-repudiation.
25
Explain the concept of a collision in hash functions and why it is significant.
KnownRevise
A collision occurs when two different inputs produce the same hash value: H(x) = H(x′) with x ≠ x′. Collisions must exist: a hash maps infinitely many inputs to a fixed number of outputs (2²⁵⁶ for SHA-256), so by the pigeonhole principle some inputs share digests. What matters is whether anyone can find them. A secure hash makes this computationally infeasible: the best generic attack is the birthday attack, needing about 2^(n/2) evaluations, so about 2¹²⁸ for SHA-256. Collisions are significant because many systems use the hash as a stand-in for the data. If an attacker can create two documents with the same hash, a signature on one is valid for the other, a certificate authority can be tricked into signing a rogue certificate, files can be swapped without changing a checksum, and deduplication or content-addressed storage can be confused. MD5 (practical collisions since 2004, exploited by the Flame malware in 2012) and SHA-1 (SHAttered, 2017) are broken for this reason.
import hashlib
def tiny_hash(data, bits=32):
# SHA-256 truncated to 32 bits: a deliberately weak hash for demonstration
return int.from_bytes(hashlib.sha256(data).digest(), "big") >> (256 - bits)
seen = {}
i = 0
while True:
msg = f"invoice-{i}".encode()
h = tiny_hash(msg)
if h in seen:
print(f"collision after {i + 1:,} messages: {seen[h]} and {msg} -> {h:08x}")
# collision after 86,733 messages: b'invoice-70535' and b'invoice-86732' -> 38c845de
break
seen[h] = msg
i += 1
print(f"birthday estimate: about {2 ** 16:,} (2^16) for a 32-bit hash; brute-forcing ONE target needs about 2^32")
Truncating SHA-256 to 32 bits makes collisions easy: one appears after tens of thousands of messages, close to the birthday estimate of about 2¹⁶ (the exact count varies with the inputs). Finding an input matching one specific digest would take about 2³² tries. With the full 256 bits, both are infeasible.
Types of Collision Attacks
Attack
Attacker’s power
Danger
Identical-prefix collision
Two messages with the same chosen prefix and different random-looking blocks
Swap documents that render differently (SHAttered PDFs)
Chosen-prefix collision
Any two chosen prefixes made to collide by appending blocks
Much more dangerous: rogue CA certificate (MD5, 2008), Flame code-signing forgery, SHA-1 “Shambles” (2020)
Second preimage
Collide with a given message
Would break existing signatures; much harder, not practical for MD5 or SHA-1
Why It Matters: Example With Signatures
1. Attacker crafts contract A ("pay 100") and contract B ("pay 100,000") with H(A) = H(B).
2. Victim signs A; the signature covers H(A).
3. Attacker presents B with the same signature: verification passes, because H(B) = H(A).
Status of Common Hash Functions
Hash
Output
Collision resistance
MD5
128 bits
Broken: collisions in seconds; chosen-prefix practical
Yes (Git added SHA-1 collision detection and is moving to SHA-256)
HMAC
Much less (HMAC-MD5 and HMAC-SHA1 are not broken in the same way, but migrate anyway)
Password hashing
Preimage resistance and slowness matter more
Non-security checksums (CRC32)
No: CRC catches accidental errors only
Pitfalls
Still using MD5 or SHA-1 for signatures, certificates or file integrity against attackers.
Truncating hashes too much (64-bit IDs collide after about 4 billion items).
Confusing collision resistance with preimage resistance: collisions are much cheaper to find.
Interview Tips
Define a collision, and say they must exist but must be infeasible to find.
Give the birthday bound 2^(n/2).
Explain the signature-forgery scenario, and cite MD5 (Flame) and SHA-1 (SHAttered).
26
Describe the birthday attack and its relevance to hash functions.
KnownRevise
The birthday attack exploits the birthday paradox: in a group of only 23 people, there is about a 50% chance that two share a birthday, even though there are 365 days. The reason is that the number of pairs grows quadratically (23 people form 253 pairs). In general, among random values from N possibilities, a collision is likely after about √N values (more precisely, about 1.18·√N for 50%). For an n-bit hash, N = 2ⁿ, so an attacker who hashes about 2^(n/2) random inputs probably finds two that collide. That is far fewer than the 2ⁿ needed to match a specific digest. Consequences: - a hash’s collision resistance is only half its length in bits, so SHA-256 gives 128-bit collision security, and a 128-bit hash such as MD5 offers at most 64 bits even without its other flaws; - 64-bit block ciphers leak after about 2³² blocks (Sweet32); - random identifiers and nonces need enough bits to avoid accidental collisions.
Read full answerHide full answer
Applies tocollision resistance, nonce and ID sizing (Python 3.12 example)
Code Example: Birthday Probabilities
import math
def p_collision(n_items, space):
# Probability that at least two of n random values (from `space` possibilities) are equal
return 1 - math.exp(-n_items * (n_items - 1) / (2 * space))
print(f"{p_collision(23, 365):.2f}") # 0.50: 23 people, shared birthday
print(f"{p_collision(70, 365):.3f}") # 0.999
for bits in (64, 128, 256):
n = math.sqrt(2 * 2 ** bits * math.log(2)) # items needed for a 50% chance
print(f"{bits}-bit hash: 50% collision chance after about 2^{math.log2(n):.1f} hashes")
# 64-bit hash: ... about 2^32.2 hashes; 128-bit: 2^64.2; 256-bit: 2^128.2
The approximation 1 − e^(−n²/2N) shows that doubling the hash length squares the work. To reach a 50% chance you need about √(2·ln 2·N) ≈ 1.18·√N items.
Collision Versus Preimage Effort
Hash size
Find any collision (birthday)
Find an input for a given digest
32 bits
About 2¹⁶ (65,000): instant
About 2³²
64 bits
About 2³²: easy
About 2⁶⁴
128 bits (MD5 size)
About 2⁶⁴: feasible for large attackers
About 2¹²⁸
160 bits (SHA-1 size)
About 2⁸⁰ generic (actual attacks about 2⁶³)
About 2¹⁶⁰
256 bits (SHA-256)
About 2¹²⁸: infeasible
About 2²⁵⁶
How an Attacker Uses It
1. Prepare a legitimate document and a fraudulent one.
2. Make 2^(n/2) harmless variations of each (spaces, invisible characters, metadata).
3. Hash all variations; look for any legitimate/fraudulent pair with equal hashes.
4. Get the legitimate variant signed; attach the signature to the fraudulent variant.
Memory-efficient versions (Pollard’s rho, parallel collision search with distinguished points) find collisions without storing every hash.
Where the Birthday Bound Matters
Area
Consequence
Hash output length
Use at least 256-bit hashes for collision resistance
Block cipher block size
64-bit blocks (3DES, Blowfish) collide after about 2³² blocks: Sweet32
Random nonces
AES-GCM 96-bit random nonces: limit about 2³² messages per key
Random IDs (UUIDv4 has 122 random bits)
Collisions negligible below about 2⁶¹ IDs
Short tokens or truncated hashes
32- or 64-bit values collide quickly at scale
MACs
Tag length bounds forgery chances and birthday-based attacks
Pitfalls
Assuming an n-bit hash gives n bits of collision security.
Using short random IDs (for example 8 hex characters = 32 bits) for millions of objects.
Running many messages through 64-bit block ciphers under one key.
Random GCM nonces without key rotation at very high message volumes.
Interview Tips
Explain the birthday paradox (23 people → 50%) and the √N rule.
State the consequence: n-bit hash → n/2-bit collision security, so SHA-256 gives 128 bits.
Mention signature forgery, Sweet32, nonce and ID sizing.
27
How does a digital signature guarantee the integrity and authenticity of a message?
KnownRevise
A digital signature binds a message to a private key using mathematics that only the key holder can perform, while anyone with the public key can check the result. Integrity and authenticity both come from what verification proves: - Integrity: the signature is computed over a cryptographic hash of the exact message. When the verifier hashes the received message and checks the signature, any change (even one bit) produces a different hash, so verification fails. Because the hash is collision resistant, the attacker cannot find a different message with the same hash. - Authenticity: producing a signature that verifies under a public key requires the corresponding private key. Secure schemes (Ed25519, ECDSA, RSA-PSS) are existentially unforgeable: without the private key, an attacker cannot create a valid signature for any new message, even after seeing many signed messages. So a valid signature shows that the key holder signed this exact message.
These guarantees rest on three conditions: the private key stays secret, the public key really belongs to the claimed signer (certificates, PKI or verified fingerprints), and the algorithms and hash are secure.
Sign: h = Hash(message) Verify: h' = Hash(received message)
sig = Sign(private_key, h) ok = Verify(public_key, h', sig)
send (message, sig) ok is true only if
- message unchanged (h' = h), and
- sig was made with the matching private key
What an Attacker Can and Cannot Do
Attacker action
Result
Change the message, keep the signature
Hash changes → verification fails (integrity)
Change the message and make a new signature with their own key
Verifies only under the attacker’s public key → wrong identity (authenticity)
Replace the signer’s public key with their own
Prevented by certificates or trusted key distribution
Reuse an old valid signed message
Not prevented by signatures alone: add timestamps, nonces or sequence numbers
Collision-resistant hash; correct verification of the whole message
Authenticity
Secret private key; unforgeable signature scheme; authentic public key
Non-repudiation
All of the above, plus evidence that only the signer controlled the key (HSMs, smart cards, audit logs) and trusted timestamps
Freshness (not replayed)
Not provided: add timestamps, nonces or counters
Real-World Uses
TLS: the server signs the handshake transcript, proving it holds the certificate’s private key.
Software updates and packages: operating systems verify signatures before installing.
Container images: Sigstore Cosign signatures checked at deployment.
JWTs (RS256, ES256, EdDSA): APIs verify that tokens were issued by the identity provider.
Documents: PDF signatures, often with trusted timestamps (RFC 3161).
Pitfalls
Verifying with a public key taken from the message itself (for example a JWT jwk header) instead of a trusted source.
Accepting alg: none or switching algorithms in JWT libraries.
Signing only part of the data, so unsigned fields can be changed.
No replay protection.
Weak hashes (MD5, SHA-1) under the signature.
Interview Tips
Explain integrity via the hash and authenticity via the private key.
Mention existential unforgeability and the need for an authentic public key.
Note that signatures do not prevent replay on their own.
28
What are RSA signatures, and how do they differ from RSA encryption?
KnownRevise
RSA uses one key pair for two different operations, run in opposite directions: - RSA encryption provides confidentiality. The sender encrypts with the recipient’s public key (c = mᵉ mod n), and only the private key holder can decrypt (m = cᵈ mod n). - RSA signatures provide integrity and authenticity. The signer applies the private key to a padded hash of the message (s = hᵈ mod n), and anyone verifies with the public key (check sᵉ mod n = padded h).
The mathematics is similar, but they are different schemes with different padding and security goals: - encryption uses OAEP (randomised, IND-CCA2 secure); - signatures use PSS (randomised, provably secure), or PKCS#1 v1.5 signature padding, which is still widely used and considered secure, unlike PKCS#1 v1.5 encryption padding.
Read full answerHide full answer
Signing is not “encrypting with the private key”. That description is misleading and has caused real bugs. Use separate key pairs for encryption and signing, and prefer modern options: Ed25519 or ECDSA for signatures, and ECDH-based or post-quantum KEMs for key exchange.
Applies to: RSA (PKCS #1 v2.2, RFC 8017)
Side-by-Side
Aspect
RSA encryption
RSA signature
Goal
Confidentiality
Integrity, authenticity, non-repudiation
Key used by the sender
Recipient’s public key
Signer’s private key
Key used by the receiver
Recipient’s private key
Signer’s public key
Input
Small message, usually a symmetric key
Hash of the message (any length)
Padding scheme
OAEP (recommended); PKCS#1 v1.5 encryption is legacy and dangerous
PSS (recommended) or PKCS#1 v1.5 signature padding
Forgeries with weak padding or weak hashes; fault attacks on CRT
The Operations (With Padding)
Encryption: c = (OAEP_pad(m, random))^e mod n [recipient public key (n, e)]
Decryption: m = OAEP_unpad(c^d mod n) [recipient private key d]
Signing: s = (PSS_encode(Hash(message), salt))^d mod n [signer private key d]
Verifying: PSS_verify(s^e mod n, Hash(message)) [signer public key (n, e)]
OpenSSL Examples
# Encryption (OAEP) of a small secret with the recipient's public key
openssl pkeyutl -encrypt -pubin -inkey bob.pub -pkeyopt rsa_padding_mode:oaep \
-pkeyopt rsa_oaep_md:sha256 -in aes.key -out aes.key.enc
openssl pkeyutl -decrypt -inkey bob.key -pkeyopt rsa_padding_mode:oaep \
-pkeyopt rsa_oaep_md:sha256 -in aes.key.enc -out aes.key
# Signature (PSS) with the signer's private key
openssl dgst -sha256 -sigopt rsa_padding_mode:pss -sign alice.key -out doc.sig doc.pdf
openssl dgst -sha256 -sigopt rsa_padding_mode:pss -verify alice.pub -signature doc.sig doc.pdf
Why Keep Them Separate
Different security proofs: using one key for both can enable cross-protocol attacks, such as tricking a decryption service into producing signatures.
Different lifecycles: signing keys may need long-term archival for verification; encryption keys may need escrow or recovery for data access.
Policy and compliance: X.509 key usage flags (digitalSignature versus keyEncipherment) separate them.
Pitfalls
Textbook RSA (no padding) for either operation.
PKCS#1 v1.5 encryption in new designs (padding oracles).
Signing raw data instead of a hash with proper encoding.
One key pair for both purposes.
Weak hashes (SHA-1) in signatures.
Interview Tips
Contrast the direction of keys: encrypt with the public key and decrypt with the private; sign with the private key and verify with the public.
Name the padding schemes: OAEP for encryption, PSS for signatures.
Say “signing is not encrypting with the private key”, and use separate keys.
29
Explain the importance of using a secure hash algorithm for digital signatures.
KnownRevise
Signature algorithms almost never sign the message directly. They sign a hash of it, because the hash is short and fixed-size, which makes signing fast for messages of any length. This makes the hash the weakest link: a signature on H(m) is a valid signature on every message with the same hash. If the hash is not collision resistant, an attacker can prepare two messages with equal hashes, get the innocent one signed, and transfer the signature to the malicious one. If it lacks second-preimage resistance, existing signatures can be reused on forged documents. Real attacks: MD5 collisions produced a rogue CA certificate (2008) and let the Flame malware fake Microsoft code-signing (2012); SHA-1 collisions (SHAttered 2017, chosen-prefix “Shambles” 2020) led browsers and CAs to ban SHA-1 certificates. Use SHA-256 or stronger (SHA-384, SHA-512, SHA-3), or schemes with built-in hashing such as Ed25519 (SHA-512).
Read full answerHide full answer
Applies toRSA-PSS, ECDSA, EdDSA, X.509 certificates, code and document signing
Why the Hash Matters
signature = Sign(private_key, Hash(message))
If Hash(A) == Hash(B):
Verify(public_key, Hash(B), signature) succeeds
=> a signature on A also "signs" B
Which Hash Property Protects What
Property
Threat prevented
Collision resistance
Attacker prepares two colliding documents and gets one signed (contracts, certificates)
Second-preimage resistance
Attacker finds a new document matching an already-signed one
Preimage resistance
Less direct for signatures; matters for related constructions
Output length
256-bit output gives 128-bit collision security; it should match the signature’s security level
Historical Failures
Year
Event
Hash
2004
First practical MD5 collisions (Wang et al.)
MD5
2008
Rogue CA certificate created using a chosen-prefix MD5 collision
MD5
2012
Flame malware forged Microsoft code-signing certificates
MD5
2017
SHAttered: two different PDFs with the same SHA-1 hash
SHA-1
2020
SHA-1 chosen-prefix collision (“SHA-1 is a Shambles”), PGP key forgery demonstrated
SHA-1
Browsers stopped accepting SHA-1 TLS certificates in 2017. Git and other systems added collision detection and migration paths.
Matching Hash and Signature Strength
Signature
Recommended hash
RSA-2048 or 3072 (PSS)
SHA-256
ECDSA P-256
SHA-256
ECDSA P-384
SHA-384
Ed25519
SHA-512 (built in)
ML-DSA (post-quantum)
SHAKE-based hashing (built in)
A strong signature algorithm with a weak hash is only as strong as the hash.
Practical Checks
# Check the signature algorithm of a certificate
openssl x509 -in cert.pem -noout -text | grep "Signature Algorithm"
# Expect e.g. sha256WithRSAEncryption, ecdsa-with-SHA256 or ED25519, never md5 or sha1
Defences
Use SHA-256 or stronger everywhere signatures are made or verified.
Reject MD5 and SHA-1 in verification code, certificate policies and JWT algorithms.
Randomised signing schemes (RSA-PSS with salt, CA serial number randomisation) make collision attacks harder to prepare.
Crypto agility: be able to change hash algorithms without redesigning the system.
Timestamp old signatures before algorithms weaken, to keep long-term validity (archive signatures).
Pitfalls
Verifiers accepting weak hashes for compatibility.
Signing a truncated or custom hash.
Hashing only part of the document (unsigned metadata can change meaning).
Assuming HMAC-SHA1 considerations apply to signatures: signatures need collision resistance; HMAC does not rely on it in the same way.
Interview Tips
Explain that signatures cover the hash, so a collision transfers the signature.
Cite MD5 (rogue CA, Flame) and SHA-1 (SHAttered).
Recommend SHA-256+ or Ed25519, matched to the signature strength, and crypto agility.
30
What is a Merkle tree, and how is it used in cryptography?
KnownRevise
A Merkle tree (hash tree, Ralph Merkle, 1979) is a binary tree where: - every leaf holds the hash of a data block; - every internal node holds the hash of its two children; - the single hash at the top is the Merkle root.
The root acts as a compact commitment to all the data: changing any block changes its leaf hash and every hash up to the root. Its key advantage is efficient inclusion proofs: to prove that one block belongs to a set of n blocks, you only need the sibling hashes along its path, which is log₂(n) hashes. A verifier who trusts the root recomputes the path. Merkle trees are used in: - blockchains (Bitcoin and Ethereum transaction roots, so light clients can verify transactions); - Certificate Transparency logs (proofs of inclusion and append-only consistency); - Git and other content-addressed systems (similar hash DAGs); - file systems and distribution (ZFS, IPFS, BitTorrent v2); - database anti-entropy (Cassandra and DynamoDB-style replica comparison); - hash-based post-quantum signatures (XMSS, LMS, SLH-DSA).
Read full answerHide full answer
Applies toMerkle trees with SHA-256 (Python 3.12 example)
Code Example: Root, Proof and Verification
import hashlib
def h(data):
return hashlib.sha256(data).digest()
def merkle_root(leaves):
level = [h(b"\x00" + leaf) for leaf in leaves] # 0x00 prefix: leaf hash
while len(level) > 1:
if len(level) % 2:
level.append(level[-1]) # duplicate the last node if odd
level = [h(b"\x01" + level[i] + level[i + 1]) for i in range(0, len(level), 2)]
return level[0]
def proof(leaves, index):
level = [h(b"\x00" + leaf) for leaf in leaves]
path = []
while len(level) > 1:
if len(level) % 2:
level.append(level[-1])
sibling = index ^ 1
path.append((level[sibling], sibling < index)) # (hash, sibling is on the left?)
level = [h(b"\x01" + level[i] + level[i + 1]) for i in range(0, len(level), 2)]
index //= 2
return path
def verify(leaf, path, root):
node = h(b"\x00" + leaf)
for sibling, is_left in path:
node = h(b"\x01" + sibling + node) if is_left else h(b"\x01" + node + sibling)
return node == root
txs = [f"tx{i}: alice->bob {i * 10}".encode() for i in range(8)]
root = merkle_root(txs)
p = proof(txs, 5)
print(root.hex()[:16], len(p), "hashes in the proof") # 349aa4e82181b099 3 (log2 of 8 leaves)
print(verify(txs[5], p, root)) # True
print(verify(b"tx5: alice->bob 5000", p, root)) # False: tampered transaction
The proof for one of 8 transactions contains just 3 sibling hashes. For a million leaves it would be 20 hashes, about 640 bytes. Leaves and internal nodes use different prefixes (0x00 and 0x01, as in Certificate Transparency, RFC 6962), so a leaf can never be passed off as an internal node (a second-preimage attack on naive Merkle trees).
Two replicas compare roots, then descend only into differing subtrees
Parallel hashing
Subtrees are hashed independently
Applications
System
How it uses Merkle trees
Bitcoin
Block headers hold the transactions’ Merkle root; SPV clients verify inclusion
Ethereum
Merkle-Patricia tries for state, transactions and receipts
Certificate Transparency
Inclusion proofs for certificates; consistency proofs show the log only grows
Git
Trees and commits form a Merkle DAG of content hashes
IPFS, BitTorrent v2
Verify pieces of files independently
Cassandra, DynamoDB-style stores
Anti-entropy repair compares Merkle trees of key ranges
ZFS, Btrfs
Checksums in parent blocks detect silent corruption
Hash-based signatures (XMSS, LMS, SLH-DSA)
The root is the public key over many one-time keys
Pitfalls
No domain separation between leaves and nodes, which allows second-preimage tricks.
Duplicating the last node for odd levels can let different leaf lists produce the same root: Bitcoin’s CVE-2012-2459 issue. Handle odd counts carefully or include the leaf count.
Trusting a root from an unauthenticated source: the proof is only as good as the root.
Weak hash functions.
Interview Tips
Describe leaves = hashes of data; parents = hashes of children; root commits to everything.
Explain O(log n) inclusion proofs.
Give uses: blockchains, Certificate Transparency, Git, replica repair, hash-based signatures.
31
What is key distribution, and what challenges does it present?
KnownRevise
Key distribution is the problem of getting cryptographic keys to the parties who need them, securely, reliably and at scale, so that only they hold them and they know whose key is whose. It is often the hardest part of cryptography: strong algorithms are useless if keys are intercepted, substituted, reused for too long or lost. The challenges: - Confidentiality in transit: symmetric keys must be shared without an eavesdropper seeing them, which is a chicken-and-egg problem, because you need a secure channel to create one. - Authenticity: public keys need not be secret, but they must be genuine, or a man-in-the-middle can substitute their own. - Scale: pairwise symmetric keys need n(n − 1)/2 keys for n parties. - Lifecycle: generation, rotation, revocation, expiry, recovery and destruction. - Trust: who vouches for keys (CAs, key distribution centres)? - Endpoint security and compromise recovery.
Solutions combine public-key key exchange (Diffie-Hellman, ECDH, KEMs), PKI and certificates, trusted key distribution centres (Kerberos), key management systems and HSMs, and protocols with forward secrecy.
Each user shares a key with the KDC, which issues session tickets
Central point of trust and failure; works well inside organisations
Public-key exchange (Diffie-Hellman, 1976)
Agree on a secret over a public channel
Needs authentication to stop MITM
PKI
CAs sign certificates binding names to keys
Trust in CAs; revocation is hard
Web of trust (PGP)
Users sign each other’s keys
Hard for non-experts
Trust on first use (SSH)
Remember the key seen first
First connection is vulnerable
Key management services (AWS KMS, Vault)
Central service generates, stores and controls key use
Access control and auditing become critical
Envelope encryption
Data keys encrypted by a master key in KMS or HSM
Master key never leaves the HSM; data keys rotate easily
Example: Envelope Encryption
1. KMS generates a data key DK; returns DK (plaintext) and Enc_MK(DK).
2. App encrypts data with DK (AES-GCM), stores ciphertext + Enc_MK(DK), discards plaintext DK.
3. To decrypt: send Enc_MK(DK) to KMS (with authorisation) -> get DK -> decrypt data.
The master key MK never leaves the KMS or HSM; access is logged and can be revoked.
Pitfalls
Hard-coded keys in source code or images.
Sending keys by email or chat.
Never rotating keys.
Unauthenticated key exchange (vulnerable to MITM).
One key for everything, so a single compromise exposes all data.
Interview Tips
Define key distribution as getting the right keys to the right parties securely.
Name the challenges: secrecy, authenticity, scale, lifecycle and trust.
Mention Diffie-Hellman, PKI, Kerberos, KMS and HSMs, envelope encryption and forward secrecy.
32
Describe Diffie-Hellman key exchange and its primary use.
KnownRevise
Diffie-Hellman (DH) key exchange (1976) lets two parties who have never met agree on a shared secret over a public channel, without ever sending the secret itself. Both agree on public parameters: a large prime p and a generator g (or an elliptic curve and base point). Then: - Alice picks a secret a and sends A = gᵃ mod p; - Bob picks a secret b and sends B = gᵇ mod p; - each combines the other’s value with their own secret: Alice computes Bᵃ, Bob computes Aᵇ, and both get g^(ab) mod p.
An eavesdropper sees g, p, A and B, but computing g^(ab) from them is believed to be hard: the Diffie-Hellman problem, related to the discrete logarithm problem. Its primary use is establishing session keys for symmetric encryption, as in TLS, SSH, IPsec, WireGuard and Signal. With fresh (ephemeral) keys per session (DHE or ECDHE) it provides forward secrecy. Plain DH is unauthenticated, so it is vulnerable to man-in-the-middle attacks unless combined with signatures, certificates or pre-shared keys.
Read full answerHide full answer
Applies tofinite-field DH (RFC 7919 groups), ECDH and X25519 (RFC 7748) (Python 3.12 toy example)
Code Example: The Exchange
import secrets
# Toy finite-field Diffie-Hellman. p is the 2^127 - 1 Mersenne prime: far too small and
# unstructured for real use (use X25519 or a 2048+ bit RFC 7919 group). g = 3 for illustration.
p = 2 ** 127 - 1
g = 3
a = secrets.randbelow(p - 2) + 1 # Alice's secret
b = secrets.randbelow(p - 2) + 1 # Bob's secret
A = pow(g, a, p) # sent over the network
B = pow(g, b, p) # sent over the network
alice_key = pow(B, a, p) # (g^b)^a
bob_key = pow(A, b, p) # (g^a)^b
print(alice_key == bob_key) # True: same secret, never transmitted
# An eavesdropper sees p, g, A and B; recovering a or b is the discrete logarithm problem.
Both sides compute the same value without sending it. The numbers here are toy-sized; real deployments use X25519 or approved groups.
Variants
Variant
Group
Notes
Finite-field DH (DHE)
Integers mod a large prime (2048–4096 bits)
Use standard groups (RFC 7919 ffdhe2048+); older TLS servers had weak 512–1024-bit groups (Logjam)
ECDH / ECDHE
Elliptic curves (P-256, P-384)
Smaller keys and faster
X25519
Curve25519
Default in TLS 1.3, SSH, WireGuard, Signal; designed for safe implementation
Hybrid post-quantum
X25519 + ML-KEM-768
Protects against future quantum attacks (Shor breaks DH)
Where It Is Used
Protocol
Use
TLS 1.3
Ephemeral ECDHE (X25519, P-256) or hybrid PQ key share; the server signs the transcript
SSH
Key exchange (curve25519-sha256, sntrup761x25519, mlkem768x25519); host keys authenticate the server
IPsec IKE
DH groups for each security association
WireGuard
Noise protocol framework built on X25519
Signal
X3DH / PQXDH and the Double Ratchet: continuous DH ratchets for forward and post-compromise security
The Man-in-the-Middle Problem
Alice --A--> Mallory --M--> Bob
Alice <--M-- Mallory <--B-- Bob
Alice's key: g^(am); Bob's key: g^(bm); Mallory knows both and relays the traffic.
TLS prevents this because the server signs the handshake (including its DH share) with a key certified for its domain. SSH uses verified host keys. Signal uses identity keys and safety-number verification.
Forward Secrecy
With ephemeral keys, a and b are deleted after the session. Even if a server’s long-term signing key leaks later, past sessions cannot be decrypted, because the DH secrets no longer exist. Static DH or RSA key transport lacks this property; TLS 1.3 removed both.
Implementation Cautions
Validate received public values (reject 0, 1, p − 1, and invalid curve points), or use X25519, which is designed to make this safe.
Use standard, large-enough groups, not custom primes.
Derive keys with a KDF (HKDF), never use the raw shared secret directly as a key.
Use constant-time implementations.
Pitfalls
Unauthenticated DH treated as secure.
Small or weak groups (Logjam, 2015: downgrade to 512-bit export DH).
Reusing ephemeral keys for many sessions, which removes forward secrecy.
Interview Tips
Walk through A = gᵃ, B = gᵇ, shared = g^(ab), based on the discrete logarithm problem.
State the use: agreeing on session keys, with ECDHE and X25519 in TLS 1.3.
Stress that it needs authentication against MITM, and mention forward secrecy and post-quantum hybrids.
33
Explain what a key escrow is and its purpose in cryptography.
KnownRevise
Key escrow is an arrangement where a copy of a cryptographic key, or the means to recover it, is held by a trusted third party or a designated internal function, so that encrypted data can be accessed under defined conditions without the key owner’s cooperation. The legitimate purposes are business continuity and recovery: - an employee leaves or loses their key; - encrypted backups must remain readable for years; - a regulator or auditor needs access to retained records; - a device is lost but its data must be recovered (for example BitLocker recovery keys stored in Entra ID or Active Directory).
The controversial version is government key escrow for lawful access, such as the 1990s US Clipper chip proposal. It was abandoned after a protocol flaw was found (Matt Blaze, 1994) and over civil-liberties concerns. Security experts broadly oppose mandated “exceptional access” because any escrow creates a high-value target and weakens security for everyone. Within organisations, escrow should apply to encryption keys, never signing keys (escrowed signing keys would destroy non-repudiation), and should use split control (Shamir secret sharing or M-of-N approvals), HSMs, and audited recovery procedures.
Read full answerHide full answer
Applies toenterprise key management and recovery
Escrow Versus Recovery Approaches
Approach
How it works
Example
Third-party escrow
A copy of the key is deposited with an external agent
Historical Clipper proposal; some legal or contractual arrangements
Internal key recovery
Keys are wrapped with a recovery key held by a security team
BitLocker and FileVault recovery keys in device management
Key backup in KMS or HSM
Encrypted key backups under HSM-protected master keys
Cloud KMS key backups, HSM backup tokens
Split knowledge (M-of-N)
Recovery needs several custodians
Shamir secret sharing; HSM quorum cards
Data recovery agents
An extra recipient key is added to each encrypted file
Windows EFS data recovery agent, PGP additional decryption keys
Example: M-of-N Recovery With Shamir’s Secret Sharing
Recovery key K is split into 5 shares; any 3 can reconstruct it; 2 or fewer reveal nothing.
Shares are held by: CISO, head of IT, legal counsel, two offline safes in different sites.
Recovery requires a ticket, approvals, and 3 custodians present -> logged and audited.
What to Escrow and What Not To
Key type
Escrow?
Reason
Data encryption keys (disk, backups, archives)
Yes, or recoverable through KMS
Losing them means losing the data
User email encryption keys (S/MIME)
Often, for enterprise recovery
Compliance and continuity
Signing keys
No
Non-repudiation requires that only the signer holds the key
TLS session keys
No
Ephemeral by design (forward secrecy)
Authentication keys and passkeys
No
Re-issue instead of recovering
Risks of Escrow
A concentrated target: the escrow store can expose everyone’s data at once.
Insider abuse: needs separation of duties, approvals and audit trails.
Scope creep: keys recovered for one purpose and used for others.
Legal compulsion: escrowed keys can be demanded by courts or governments in various jurisdictions.
Complexity: more parties and processes mean more ways to fail.
Good Practice
Prefer data recovery through KMS-wrapped keys over raw key copies.
Separate encryption and signing keys, and escrow only encryption keys.
Require multi-person approval (M-of-N), and log and review every recovery.
Protect escrow material in HSMs or offline safes.
Document policies: when recovery is allowed, who approves, and how users are informed.
Test recovery regularly.
Pitfalls
Escrowing signing keys.
A single administrator able to recover any key alone.
Recovery keys stored in plain text in spreadsheets or tickets.
No recovery plan at all, so encrypted backups become unreadable after staff changes.
Interview Tips
Define escrow as a trusted party holding keys for authorised recovery.
Separate enterprise recovery (legitimate) from government backdoors (controversial: Clipper).
Stress never escrow signing keys, plus M-of-N control and auditing.
34
How do certificate authorities help in securing communications over the internet?
KnownRevise
Certificate authorities (CAs) solve the public-key authenticity problem: when your browser connects to bank.example, how does it know the public key it receives belongs to the real bank and not an attacker in the middle? A CA verifies that the requester controls the domain (and, for some certificates, checks the organisation’s identity). It then issues a certificate: a document binding the domain name to the public key, signed with the CA’s private key. Browsers and operating systems ship a trust store of root CAs. During the TLS handshake the server presents its certificate chain, and the client verifies the signatures up to a trusted root, checks the hostname, validity period, key usage and revocation status, and confirms the server holds the private key by checking its signature over the handshake. Only then are the derived session keys trusted. CAs therefore underpin HTTPS, code signing, S/MIME email and mTLS. Their own trustworthiness is enforced by audits, the CA/Browser Forum baseline requirements, Certificate Transparency logs and browser root programmes.
Read full answerHide full answer
Applies toWeb PKI, TLS 1.3, ACME (RFC 8555)
What a CA Does
Function
Detail
Validation
Domain validation via ACME challenges (HTTP-01, DNS-01, TLS-ALPN-01); organisation and extended validation for some certificates
Issuance
Signs the certificate (subject alternative names, public key, validity, extensions)
Logging
Submits to Certificate Transparency logs; embeds signed certificate timestamps (SCTs)
Revocation
Publishes CRLs and OCSP responses
Key protection
Root keys offline in HSMs; issuance from intermediate CAs
Client Server (shop.example)
ClientHello (key share) ------------->
<------------- ServerHello (key share), Certificate chain,
CertificateVerify (signature over the handshake), Finished
Client checks:
1. leaf signed by intermediate, intermediate signed by a root in the trust store
2. "shop.example" is in the certificate's subject alternative names
3. now is within notBefore..notAfter; key usage allows server authentication
4. not revoked; CT SCTs present (browsers require them)
5. CertificateVerify signature checks out with the leaf's public key
=> the session keys are shared with the genuine shop.example, not an interceptor
Certificate Types
Type
Validation
Shown to users
Domain validated (DV)
Control of the domain
Padlock
Organisation validated (OV)
Domain plus organisation checks
Same padlock; details in the certificate
Extended validation (EV)
Stricter organisation vetting
Browsers no longer show special indicators
Most of the web uses free, automated DV certificates from Let’s Encrypt and others via ACME.
Safeguards Against CA Failure
Mechanism
Protects against
Certificate Transparency
Mis-issued certificates going unnoticed (domain owners monitor the logs)
CAA DNS records
CAs not listed by the domain owner refusing to issue
Short certificate lifetimes
Long exposure from stolen keys or bad issuance (moving to 47 days by 2029)
Root programme removals
Distrust of misbehaving CAs (DigiNotar 2011, Symantec 2017–18)
Expired certificates: automate renewal with ACME and monitor expiry.
Over-broad wildcard certificates whose private key sits on many servers.
Trusting extra root CAs added by malware or by careless corporate proxies.
Interview Tips
Explain that CAs bind identities to public keys by signing certificates.
Walk through the client validation steps in the TLS handshake.
Mention ACME, Certificate Transparency, CAA and revocation, and DigiNotar as a failure case.
35
What is forward secrecy, and what protocols use this property?
KnownRevise
Forward secrecy (also called perfect forward secrecy, PFS) means that compromising a long-term key does not compromise past session keys. Recorded traffic from earlier sessions stays confidential even if the server’s private key is stolen later. It is achieved by deriving each session’s keys from ephemeral key exchanges (DHE, ECDHE, X25519): both sides generate fresh key pairs per session, use them once and delete them. The long-term key is used only to authenticate the exchange (sign it), never to transport the session key. Without forward secrecy, as in TLS RSA key transport, an attacker who records encrypted traffic and later obtains the server’s RSA key (through a breach, a legal order or a bug like Heartbleed) can decrypt everything recorded. Protocols with forward secrecy include TLS 1.3 (mandatory), TLS 1.2 with ECDHE suites, SSH, IPsec/IKEv2 with PFS groups, WireGuard, Signal (Double Ratchet, which adds post-compromise security), and QUIC/HTTP/3.
Read full answerHide full answer
Applies toTLS 1.2/1.3, SSH, IPsec, WireGuard, Signal
With and Without Forward Secrecy
Without (TLS 1.2 RSA key transport):
client encrypts pre-master secret with the server's long-term RSA public key
-> attacker records traffic; years later steals the RSA private key
-> decrypts the pre-master secret -> derives session keys -> reads all recorded sessions
With (ECDHE):
client and server each make ephemeral X25519 keys; the server SIGNS its share with its long-term key
session keys = KDF(ECDH(ephemeral_c, ephemeral_s)); ephemeral private keys are deleted
-> stealing the long-term key later only allows impersonation in FUTURE sessions,
not decryption of past ones
Protocols
Protocol
Forward secrecy
TLS 1.3
Always: only (EC)DHE or PSK-with-(EC)DHE key exchange; RSA key transport removed
TLS 1.2
Only with ECDHE-* or DHE-* cipher suites
SSH
Yes: ephemeral DH or ECDH per connection (curve25519, hybrid post-quantum)
IPsec IKEv2
IKE SA uses DH; child SAs need “PFS” enabled for fresh DH per rekey
WireGuard
Yes: Noise framework with ephemeral keys; rekeys every few minutes
Signal, WhatsApp
Yes, per message (Double Ratchet), plus post-compromise healing
Tools such as SSL Labs or testssl.sh report forward secrecy support directly.
Practical Caveats
Caveat
Explanation
Session tickets
TLS session resumption tickets are encrypted with a server ticket key; if that key is long-lived and stolen, resumed sessions can be decrypted. Rotate ticket keys frequently.
0-RTT data in TLS 1.3
Early data is encrypted with keys from a previous session and is not forward secret (and may be replayed)
Key reuse
Reusing “ephemeral” DH keys across many connections weakens the guarantee
Endpoint compromise
If an attacker controls the endpoint during a session, forward secrecy cannot help
Quantum computers
Recorded ECDHE sessions could be decrypted by a future quantum computer, hence hybrid post-quantum key exchange
Pitfalls
Allowing TLS 1.2 RSA key-exchange suites for compatibility.
Long-lived session ticket keys shared across a fleet without rotation.
TLS-inspecting middleboxes that require static keys (for example “visibility” modes that disable forward secrecy).
Interview Tips
Define it as past sessions stay secret even if long-term keys leak later.
Explain that it comes from ephemeral (EC)DH, with long-term keys used only for authentication.
Name TLS 1.3, SSH, WireGuard, Signal, and mention session tickets and 0-RTT as caveats.
36
Explain the role of cryptography in user authentication.
KnownRevise
Authentication proves who someone is, and cryptography makes each step trustworthy: - Password storage: passwords are stored as slow, salted, memory-hard hashes (Argon2id, scrypt, bcrypt), so a database breach does not reveal them. - Secure transport:TLS protects credentials and tokens in transit and authenticates the server, to stop phishing-by-interception. - Challenge-response: the user proves possession of a secret without sending it. Examples are passkeys and WebAuthn (the authenticator signs a server challenge with a private key that never leaves the device), SSH public-key login, Kerberos and SCRAM. - One-time codes:TOTP and HOTP (HMAC-based) codes from a shared secret. - Sessions and tokens: after login, the server issues random session IDs or signed tokens (JWTs signed with HMAC or asymmetric keys, signed cookies), which must be unforgeable and tamper-evident. - Federation:OAuth 2.0 and OpenID Connect use signed ID tokens, PKCE hashes and TLS; SAML uses XML signatures. - Certificates:mutual TLS and smart cards (PIV) authenticate with certificates and private keys.
Read full answerHide full answer
Applies topassword, token, passkey and certificate authentication (Python 3.12 example)
Code Example: Storing and Verifying Passwords
import hashlib
import hmac
import secrets
N, R, P = 2 ** 14, 8, 1 # scrypt cost parameters (memory-hard); tune for your hardware
def hash_password(password):
salt = secrets.token_bytes(16) # unique per user
key = hashlib.scrypt(password.encode(), salt=salt, n=N, r=R, p=P, dklen=32)
return f"scrypt${N}${R}${P}${salt.hex()}${key.hex()}" # store parameters with the hash
def verify_password(password, stored):
_, n, r, p, salt, key = stored.split("$")
candidate = hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt),
n=int(n), r=int(r), p=int(p), dklen=32)
return hmac.compare_digest(candidate.hex(), key)
record = hash_password("correct horse battery staple")
print(record.split("$")[:4]) # ['scrypt', '16384', '8', '1']
print(verify_password("correct horse battery staple", record)) # True
print(verify_password("Tr0ub4dor&3", record)) # False
print(hash_password("same") != hash_password("same")) # True: different salts
Each user gets a unique random salt, so identical passwords produce different hashes and precomputed tables are useless. scrypt is deliberately slow and memory-hard, so offline guessing is expensive. The parameters are stored with the hash, so they can be raised later. For new systems Argon2id (through a library such as argon2-cffi) is the first choice; scrypt is shown because it is in Python’s standard library.
Cryptographic Building Blocks per Step
Step
Cryptography used
Purpose
Sending credentials
TLS 1.3
Confidentiality and server authentication
Storing passwords
Argon2id, scrypt, bcrypt, PBKDF2 + salt (+ optional pepper in an HSM)
Make stolen hashes hard to crack
Passkeys and WebAuthn
ECDSA P-256 or Ed25519 signatures over a challenge, bound to the website origin
Phishing-resistant, no shared secret on the server
SSH keys
Signatures over session data
Passwordless login
TOTP and HOTP
HMAC-SHA1 (or SHA-256) of a time-step counter
Second factor
Session IDs
CSPRNG, 128+ bits
Unguessable sessions
Signed tokens (JWT, cookies)
HMAC-SHA256, RS256, ES256, EdDSA
Tamper-evident claims
OAuth and OIDC
Signed ID tokens, PKCE (SHA-256), TLS
Delegated and federated login
Kerberos
Symmetric tickets from a KDC
Enterprise single sign-on
Mutual TLS, smart cards
X.509 certificates and private keys
Device and user authentication
Challenge-Response (Passkey) Flow
1. Server -> browser: random challenge (32 bytes), relying party ID "example.com"
2. Authenticator: user verification (biometric or PIN), then signs
(clientData incl. challenge + origin) with the private key registered for example.com
3. Server: verifies the signature with the stored public key, checks challenge, origin, counter
=> no secret crosses the network; a phishing site has a different origin, so it gets no valid signature
Pitfalls
Fast hashes (MD5, SHA-256) or unsalted password hashes.
Encrypting passwords (reversible) instead of hashing them.
Non-constant-time comparisons of hashes, tokens or codes.
Weak session randomness, or tokens without expiry.
JWT pitfalls: accepting alg: none, algorithm confusion, not checking audience and expiry.
SMS codes as the only second factor (SIM swapping); prefer passkeys or authenticator apps.
Interview Tips
Walk through storage (salted slow hashes), transport (TLS), proof (challenge-response) and sessions (random IDs or signed tokens).
Mention passkeys as phishing-resistant public-key authentication.
Cover TOTP via HMAC and signed tokens, plus constant-time comparisons.
37
What is multi-factor authentication, and how is cryptography involved?
KnownRevise
Multi-factor authentication (MFA) requires two or more independent kinds of evidence: - something you know (a password or PIN); - something you have (a phone, security key or smart card); - something you are (a fingerprint or face).
Stealing one factor, typically a phished or leaked password, is then not enough. Cryptography is what makes the possession factor work: - TOTP and HOTP codes are HMACs of a shared secret and a time step or counter; - push approvals are signed messages bound to a device key; - FIDO2/WebAuthn security keys and passkeys use public-key signatures over a server challenge, bound to the website’s origin; - smart cards (PIV/CAC) hold X.509 certificates and private keys in tamper-resistant chips.
Read full answerHide full answer
Biometrics usually unlock a local private key rather than being sent to the server. The strength of MFA varies a lot: SMS codes can be intercepted through SIM swaps and phished; TOTP and push can be phished in real time or bombarded with requests (“MFA fatigue”); FIDO2 and passkeys are phishing-resistant, because the signature only works for the real origin.
import hashlib
import hmac
import struct
def hotp(secret, counter, digits=6, digest=hashlib.sha1):
mac = hmac.new(secret, struct.pack(">Q", counter), digest).digest()
offset = mac[-1] & 0x0F # dynamic truncation (RFC 4226)
code = struct.unpack(">I", mac[offset:offset + 4])[0] & 0x7FFFFFFF
return str(code % 10 ** digits).zfill(digits)
def totp(secret, unix_time, step=30, digits=6):
return hotp(secret, unix_time // step, digits) # counter = number of 30 s steps
secret = b"12345678901234567890" # RFC 6238 test secret
print(totp(secret, 59, digits=8)) # 94287082 (RFC 6238 test vector)
print(totp(secret, 1111111109, digits=8)) # 07081804 (RFC 6238 test vector)
def verify(secret, code, now, window=1):
# Accept the current step and one step either side for clock drift; compare in constant time
return any(hmac.compare_digest(totp(secret, now + d * 30), code) for d in range(-window, window + 1))
now = 1_762_300_000
print(verify(secret, totp(secret, now), now), verify(secret, "000000", now)) # True False
The server and the authenticator app share a secret (from the QR code at enrolment). Both compute HMAC(secret, current 30-second step) and truncate it to digits. The outputs match the RFC 6238 test vectors. Verification allows a small clock-drift window and compares in constant time. Production servers also rate-limit attempts and reject reuse of a code within its window.
MFA Methods Compared
Method
Cryptography
Phishing-resistant?
Main weaknesses
SMS or voice codes
None (codes delivered over the phone network)
No
SIM swap, SS7 interception, real-time phishing
Email codes or links
Random tokens
No
Email account compromise
TOTP / HOTP apps
HMAC with a shared secret
No
Real-time phishing proxies; secrets stolen from the server database
Push notifications
Device key pairs, signed approvals
Partly (number matching helps)
MFA fatigue, real-time phishing
FIDO2 security keys, passkeys
ECDSA or Ed25519 signatures bound to the origin; private key in secure hardware
Yes
Account recovery processes; lost devices
Smart cards (PIV/CAC)
X.509 certificates, private keys on a chip
Yes (with mutual TLS or certificate-based login)
Infrastructure cost
Why FIDO2 Resists Phishing
Real site: challenge from https://bank.example -> key for bank.example signs (challenge, origin)
Phishing site: https://bank-example.login.co asks for a login
-> the authenticator has no key for that origin, or the signed origin doesn't match
-> the attacker cannot replay anything useful to the real bank
Implementation Advice
Area
Advice
Offer
Passkeys and security keys first; TOTP as a fallback; avoid SMS-only
Phishing-resistant MFA for administrators and privileged access (CISA and NIST AAL3 guidance)
Pitfalls
Weak recovery flows that bypass MFA (call the help desk, receive a reset link).
SMS as the only factor for high-value accounts.
Storing TOTP secrets in plain text.
Two factors of the same kind (password + security question is not MFA).
Unlimited push prompts.
Interview Tips
Define the three factor categories, and why independence matters.
Explain TOTP as HMAC over a time counter, and FIDO2 as origin-bound signatures.
Rank methods by phishing resistance, and mention recovery flows as a common weak spot.
38
Describe the OAuth 2.0 protocol and its use cases in authentication.
KnownRevise
OAuth 2.0 (RFC 6749) is an authorisation framework. It lets a user grant an application (the client) limited access to resources on another service (the resource server) without sharing their password. An authorisation server authenticates the user, asks for consent to specific scopes, and issues an access token, often short-lived, sometimes with a refresh token. The client presents the token to the API. OAuth itself is about authorisation (“what may this app do?”), not authentication (“who is the user?”). Login is provided by OpenID Connect (OIDC), a layer on top that adds a signed ID token (a JWT) describing the user. Modern best practice, consolidated in OAuth 2.1 and the OAuth security best current practice (RFC 9700), is the authorization code flow with PKCE for all clients, plus client credentials for service-to-service calls and the device flow for TVs and command-line tools. The implicit and password grants are deprecated. Cryptography appears throughout: TLS, PKCE hashes, signed JWTs, state and nonce values, and optionally sender-constrained tokens (DPoP, mTLS).
1. Client creates code_verifier (random) and code_challenge = BASE64URL(SHA-256(code_verifier))
2. Browser -> /authorize?response_type=code&client_id=..&redirect_uri=..&scope=photos.read
&state=<random>&code_challenge=<challenge>&code_challenge_method=S256
3. User logs in and consents; AS redirects back: redirect_uri?code=<code>&state=<same random>
4. Client checks state, then POST /token: code + code_verifier (+ client authentication if confidential)
5. AS checks SHA-256(code_verifier) == stored challenge -> returns access_token (+ refresh_token,
+ id_token if OIDC scope "openid")
6. Client calls API: Authorization: Bearer <access_token>
Code Example: PKCE Values
import base64
import hashlib
import secrets
def b64url(data):
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def make_pair():
verifier = b64url(secrets.token_bytes(32)) # 43 chars, kept by the client
challenge = b64url(hashlib.sha256(verifier.encode()).digest()) # sent in the authorize request
return verifier, challenge
# RFC 7636 Appendix B test vector
verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
print(b64url(hashlib.sha256(verifier.encode()).digest()))
# E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
v, c = make_pair()
print(len(v), len(c)) # 43 43
# The server stores c with the authorization code. At the token endpoint the client sends v,
# and the server checks SHA-256(v) == c, so a stolen code alone is useless.
PKCE protects against stolen authorisation codes (for example intercepted by a malicious app on a phone): without the verifier, the code cannot be exchanged for tokens.
Grant Types
Grant
Use case
Status
Authorization code + PKCE
Web apps, single-page apps, mobile and desktop apps
Recommended for all
Client credentials
Machine-to-machine (backend services, jobs)
Recommended
Device authorization (RFC 8628)
Smart TVs, CLIs, devices with limited input
Recommended
Refresh token
Obtain new access tokens without user interaction
Use with rotation or sender-constraining
Implicit
Old SPAs (tokens in the URL fragment)
Deprecated
Resource owner password
App collects the user’s password
Deprecated
Use Cases
Use case
Mechanism
“Sign in with Google/Microsoft/Apple”
OIDC (on top of OAuth)
Third-party app accessing your data (calendar, GitHub repos)
OAuth scopes and consent
Single sign-on across company apps
OIDC with an identity provider
Microservice-to-microservice calls
Client credentials, token exchange (RFC 8693)
API gateways validating callers
JWT access tokens checked against the provider’s keys (JWKS)
CLI or TV login
Device flow
Validating Tokens
Check the signature with keys from the issuer’s JWKS endpoint (allow only expected algorithms).
Check iss, aud, exp, nbf, and for ID tokens the nonce.
Check scopes or roles for the requested operation.
For opaque tokens, use introspection (RFC 7662).
Pitfalls
Using OAuth access tokens as proof of login without OIDC: tokens issued to another client can be replayed (the “confused deputy” problem). Check the audience.
Missing state, which allows CSRF; missing PKCE.
Open redirect URIs or loose matching of redirect URIs.
Long-lived bearer tokens in browser storage, exposed to XSS; prefer short lifetimes, a backend-for-frontend, or DPoP.
Skipping JWT signature or audience checks.
Interview Tips
Say clearly: OAuth is authorisation; OIDC adds authentication.
Describe the authorization code + PKCE flow, and client credentials for services.
Mention state, PKCE, token validation (iss, aud, exp) and the deprecated grants.
39
Explain role-based access control (RBAC) and its cryptographic requirements.
KnownRevise
Role-based access control (RBAC) grants permissions to roles (for example viewer, editor, billing-admin) and assigns users or services to roles, rather than granting permissions to each user directly. A request is allowed if one of the caller’s roles has the needed permission on the resource. RBAC simplifies administration (change a role, not hundreds of users), supports least privilege and separation of duties (no single role can both create and approve payments), and eases audits. RBAC is an access-control model, not cryptography, but enforcing it securely depends on cryptography: - authenticating who the caller is: passwords stored as salted hashes, MFA, passkeys, mTLS certificates; - protecting the role claims that travel with requests: signed tokens (JWTs with RS256, ES256 or EdDSA, SAML assertions), with expiry and audience checks; - securing transport with TLS; - protecting the policy store and audit logs against tampering: signatures, hash-chained or append-only logs; - cryptographic enforcement where the server cannot be trusted: encrypting data per role with keys only that role can access (envelope encryption, attribute-based encryption).
Read full answerHide full answer
Applies toRBAC in applications, cloud IAM and Kubernetes
Core Concepts
Concept
Meaning
Permission
An allowed action on a resource type (invoice:approve)
Role
A named set of permissions (finance-approver)
Assignment
A user or group mapped to roles, optionally within a scope (team, project, namespace)
Session
The roles active for a given login (NIST RBAC model)
The group name comes from the user’s authenticated identity: a signed OIDC token or a client certificate. Kubernetes trusts it only because the token signature or certificate chain is verified.
Signed and short-lived tokens (JWT, SAML); verify signature, issuer, audience, expiry; never trust unsigned role headers
Service-to-service calls
mTLS or workload identity (SPIFFE certificates, cloud IAM tokens)
Transport
TLS everywhere, so tokens cannot be stolen in transit
Policy and role assignments
Integrity protection, change approval, signed configuration (GitOps with signed commits)
Audit logs
Tamper-evident logs: hash chaining, write-once storage, signed log batches
Data protection by role
Envelope encryption with KMS key policies per role; client-side encryption for zero-trust storage
Secrets for privileged roles
HSM- or KMS-protected keys; short-lived credentials (just-in-time access)
RBAC and Related Models
Model
Decision based on
Example
RBAC
Roles
Kubernetes RBAC, most SaaS admin consoles
ABAC
Attributes (department, location, data label, time)
AWS IAM conditions, XACML
ReBAC
Relationships (owner of, member of)
Google Zanzibar, OpenFGA
Attribute-based encryption
Attributes enforced by cryptography
Decrypt only if attributes satisfy a policy
Many systems combine RBAC with attribute or relationship checks.
Pitfalls
Trusting role claims from the client (an unsigned X-Role: admin header, or a JWT whose signature is not checked).
Role explosion: hundreds of near-duplicate roles that nobody can audit.
Over-privileged roles and permanent admin assignments; use just-in-time elevation.
Long-lived tokens that keep roles after a user is removed.
Unprotected audit logs that an attacker can edit.
Interview Tips
Define RBAC as permissions → roles → users, with least privilege and separation of duties.
Explain that RBAC relies on cryptography for authentication, signed role claims, TLS and tamper-evident logs.
Mention cryptographic enforcement (per-role keys) and the ABAC and ReBAC alternatives.
40
How does HTTPS utilize cryptography to secure communications over the web?
KnownRevise
HTTPS is HTTP sent over TLS. TLS uses cryptography to provide three guarantees: - Authentication of the server: the server presents an X.509 certificate chain signed by a trusted CA, binding its domain to a public key. It proves it owns the matching private key by signing the handshake. - Confidentiality: client and server run an ephemeral key exchange (ECDHE with X25519 or P-256, increasingly a hybrid with ML-KEM). They derive shared session keys with HKDF, and encrypt all HTTP data (URL paths, headers, cookies, bodies) with an AEAD cipher: AES-GCM or ChaCha20-Poly1305. - Integrity: every encrypted record carries an authentication tag, so any change is detected, and the Finished messages bind the whole handshake, which prevents downgrade tampering.
Ephemeral key exchange gives forward secrecy. TLS 1.3 does a full handshake in one round trip and removes legacy algorithms. HSTS stops downgrades to plain HTTP, and Certificate Transparency exposes mis-issued certificates. What stays visible to observers: the IP addresses, the domain name in SNI (unless Encrypted Client Hello is used), and traffic sizes and timing.
Read full answerHide full answer
Applies toTLS 1.3 (RFC 8446), HTTP/1.1, HTTP/2 and HTTP/3 (QUIC)
The TLS 1.3 Handshake
Client Server
ClientHello: TLS 1.3, cipher suites, key_share (X25519 / X25519MLKEM768), SNI
-------------------------------->
ServerHello: chosen suite, key_share
{EncryptedExtensions}
{Certificate chain}
{CertificateVerify: signature over the transcript}
{Finished: HMAC over the transcript}
<--------------------------------
{Finished}
-------------------------------->
[HTTP request/response encrypted with AEAD] <=====================> [ ... ]
{ } = encrypted with handshake keys; [ ] = encrypted with application keys
It does not make the website itself trustworthy: phishing sites have valid certificates too.
It does not protect data at rest on the server, or against compromised endpoints.
It does not hide who is talking to whom or traffic patterns.
Pitfalls
Disabling certificate checks in clients.
Mixed content (HTTP resources on HTTPS pages).
Legacy protocol versions (SSLv3, TLS 1.0 and 1.1) and weak ciphers left enabled.
Expired certificates: automate with ACME.
TLS terminated at a proxy with plain HTTP to the back end over untrusted networks.
Interview Tips
Map the guarantees: authentication (certificates and signatures), confidentiality (ECDHE + AEAD) and integrity (AEAD tags, Finished).
Walk through the TLS 1.3 handshake and mention forward secrecy.
Add HSTS, Certificate Transparency and ECH, and what HTTPS does not protect.
41
What is a TLS certificate, and how does it establish a secure session?
KnownRevise
A TLS certificate (still often called an “SSL certificate”) is an X.509 document that binds a server’s identity, its domain names in the Subject Alternative Name extension, to a public key. It also holds a validity period and allowed uses, and is digitally signed by a certificate authority. On its own the certificate is public and proves nothing; it matters in the TLS handshake: 1. The server sends its certificate chain. 2. The client validates it: the chain leads to a trusted root, the hostname matches, the dates are valid, the key usage fits, and the certificate is not revoked. 3. The server proves it holds the matching private key by signing the handshake transcript (CertificateVerify in TLS 1.3). 4. Meanwhile both sides run an ephemeral key exchange (ECDHE). Because the server’s signature covers that exchange, the client knows the resulting session keys are shared with the genuine server, not an attacker in the middle. 5. All further traffic is encrypted and authenticated with AEAD using those keys.
The certificate’s key is used for authentication only; in TLS 1.3 it never encrypts session keys, which gives forward secrecy.
1. ClientHello: supported suites + ephemeral key share (X25519) + SNI "shop.example"
2. ServerHello: chosen suite + its ephemeral key share
-> both compute the ECDHE shared secret -> handshake keys (HKDF)
3. Server (encrypted): Certificate chain + CertificateVerify = Sign(cert private key, transcript hash)
4. Client: validates chain + hostname + dates + revocation; verifies CertificateVerify with the cert's public key
5. Both send Finished (HMAC over the transcript) -> application keys derived
6. HTTP data flows encrypted with AES-GCM or ChaCha20-Poly1305
Getting and Managing Certificates
Task
How
Obtain
ACME clients (Certbot, Caddy, cert-manager, Traefik) with Let’s Encrypt or other CAs; CSR to a commercial CA
Key type
ECDSA P-256 (smaller, faster) or RSA 2048/3072 for older clients
Install
Serve the full chain (leaf + intermediates), not just the leaf
Renew
Automatically, well before expiry; lifetimes shrink to 47 days by 2029
Protect the key
File permissions, HSM or cloud certificate managers; never commit keys
Monitor
Expiry alerts; Certificate Transparency monitoring for unexpected issuance
Pitfalls
Missing intermediate certificates, which breaks some clients.
Hostname mismatch (certificate for example.com used on api.example.com).
Expired certificates causing outages.
Private keys shared widely (one wildcard key on many servers).
Clients that skip validation.
Interview Tips
Define a certificate as a CA-signed binding of domain names to a public key.
Explain that the handshake signature proves possession, and that ECDHE creates the session keys.
List the client validation checks, and mention ACME automation and full chains.
42
Explain how cryptography is used in blockchain technology.
KnownRevise
A blockchain is a shared, append-only ledger kept by many participants who do not trust each other. Cryptography provides its core guarantees: - Hash functions (SHA-256 in Bitcoin, Keccak-256 in Ethereum) chain the blocks: each block contains the hash of the previous block, so changing old data changes every later hash and is immediately detectable. - Merkle trees summarise all transactions in a block in one root hash, so light clients can verify a transaction’s inclusion with a short proof. - Digital signatures (ECDSA or Schnorr over secp256k1 in Bitcoin and Ethereum, Ed25519 in Solana and others) authorise transactions: only the holder of an account’s private key can spend its funds. Addresses are derived by hashing public keys. - Proof of work uses hash puzzles to make block creation expensive, so rewriting history needs most of the network’s computing power. Proof of stake uses signatures from validators with funds at stake. - Advanced cryptography adds more: zero-knowledge proofs (zk-rollups, Zcash), BLS signature aggregation (Ethereum consensus), and threshold signatures and MPC wallets.
Read full answerHide full answer
Applies toBitcoin- and Ethereum-style blockchains (Python 3.12 toy example)
Code Example: Hash Chain With Proof of Work
import hashlib
import json
def block_hash(block):
return hashlib.sha256(json.dumps(block, sort_keys=True).encode()).hexdigest()
def mine(prev_hash, txs, difficulty=4):
nonce = 0
while True: # proof of work: find a hash with leading zeros
block = {"prev": prev_hash, "txs": txs, "nonce": nonce}
h = block_hash(block)
if h.startswith("0" * difficulty):
return block, h
nonce += 1
chain = []
prev = "0" * 64
for txs in (["alice->bob 5"], ["bob->carol 2"], ["carol->dave 1"]):
block, prev = mine(prev, txs)
chain.append(block)
print(block["nonce"], prev[:16]) # e.g. 6312 00005513f0868588: tens of thousands of tries
def valid(chain):
prev = "0" * 64
for block in chain:
if block["prev"] != prev or not block_hash(block).startswith("0000"):
return False
prev = block_hash(block)
return True
print(valid(chain)) # True
chain[0]["txs"] = ["alice->bob 500"] # tamper with history
print(valid(chain)) # False: block 0's hash changed, breaking the links
Each block stores the previous block’s hash and a nonce found by brute force so that its own hash starts with zeros (the proof of work). Changing an old transaction changes that block’s hash, which no longer matches the prev field of the next block. An attacker would have to redo the work for every following block faster than the honest network.
Where Each Primitive Is Used
Primitive
Role
Examples
Hash functions
Block linking, transaction IDs, addresses, mining
SHA-256 (Bitcoin), Keccak-256 (Ethereum)
Merkle trees / tries
Commit to transactions and state; light-client proofs
Private transactions; scaling with validity proofs
Zcash (zk-SNARKs), zk-rollups (SNARKs and STARKs)
Commitments
Hide values while binding to them
Pedersen commitments (Monero, Mimblewimble)
Threshold signatures, MPC
Shared custody without a single key
Institutional wallets
How a Transaction Is Authorised
1. Wallet builds a transaction: inputs (coins owned), outputs (recipient addresses), fee
2. Wallet signs the transaction hash with the private key for the inputs' addresses
3. Nodes verify: signature valid for the public key, public key hashes to the address that owns the coins,
coins not already spent
4. Miners or validators include it in a block; the block hash chain makes it hard to reverse
Limits and Risks
Private key = ownership: lost keys mean lost funds; stolen keys mean irreversible theft.
Quantum computers would break ECDSA and Schnorr; post-quantum migration is an open problem for blockchains.
Smart-contract bugs are not prevented by cryptography.
Privacy: most chains are pseudonymous, not anonymous; transaction graphs can be analysed.
51% attacks on smaller proof-of-work chains.
Pitfalls
Weak randomness in wallets, which has led to stolen keys.
ECDSA nonce reuse in signing implementations.
Storing seed phrases online.
Interview Tips
Name the core pieces: hash chaining, Merkle trees, digital signatures and consensus (PoW or PoS).
Explain why tampering is detectable and expensive.
Mention zero-knowledge proofs, BLS aggregation and the key-management and quantum risks.
43
Describe the use of cryptographic primitives in password hashing.
KnownRevise
Password hashing turns a password into a value that can verify future logins but is hard to reverse if the database leaks. Because passwords have low entropy, a normal fast hash is not enough: attackers try billions of guesses per second on GPUs. Password hashing combines several primitives: - a one-way function: a hash such as SHA-256 or BLAKE2, or a block cipher, as the core; - a unique random salt per password (16 bytes from a CSPRNG), so identical passwords hash differently and precomputed rainbow tables are useless; - key stretching: thousands to millions of internal iterations make each guess slow; - memory hardness (scrypt, Argon2): each guess needs lots of RAM, which defeats cheap GPU and ASIC parallelism; - optionally a pepper: a secret key kept outside the database (in an HSM or secret store), applied as an HMAC or by encrypting the hash; - constant-time comparison when verifying.
Recommended functions, in order: Argon2id, scrypt, bcrypt, and PBKDF2-HMAC-SHA256 where FIPS compliance is required (with high iteration counts).
The algorithm, parameters and salt are stored with the hash, so verification can recompute it and the parameters can be raised later (rehash on next successful login).
Verification Flow
login(password):
record = db.get(user) -> algorithm, params, salt, stored_hash
candidate = KDF(password, salt, params) (optionally HMAC with pepper)
if constant_time_equal(candidate, stored_hash):
if params weaker than current policy: store KDF(password, new_salt, new_params)
success
else: failure (same response and similar timing whether or not the user exists)
PasswordHasher uses Argon2id with sensible defaults, generates salts, and offers check_needs_rehash for parameter upgrades.
Salt Versus Pepper
Salt
Pepper
Unique per password
Yes
No (one per application or per key version)
Secret
No (stored with the hash)
Yes (stored separately, ideally in an HSM or KMS)
Defends against
Rainbow tables; identical-password detection
Offline cracking when only the database leaks
Pitfalls
Fast hashes, or homemade schemes such as sha256(salt + password) once.
Global or short salts.
Encrypting passwords instead of hashing them (reversible if the key leaks).
bcrypt’s 72-byte limit with long passphrases or pre-hashing mistakes (pre-hashing raw binary can cut at a zero byte).
Parameters never raised as hardware gets faster.
Password length limits that are too short, or silently truncating passwords.
Interview Tips
List the primitives: one-way function, salt, stretching, memory hardness, optional pepper.
Recommend Argon2id, then scrypt, bcrypt, PBKDF2 (FIPS), with parameters stored with the hash.
Explain why fast hashes fail (GPU guessing rates) and constant-time verification.
44
How do secure cookies work, and what cryptographic measures are involved?
KnownRevise
A cookie is data the server asks the browser to store and send back with each request, usually a session identifier. “Secure cookies” combine browser attributes with cryptographic protection: - Secure: the cookie is sent only over HTTPS, so TLS encrypts it in transit. - HttpOnly: JavaScript cannot read it, which limits theft through XSS. - SameSite=Lax or Strict: limits cross-site sending, which reduces CSRF. - Scoping: the __Host- prefix, Path and Domain. - Lifetime: Max-Age or Expires.
The cryptographic measures depend on what the cookie holds: - an opaque session ID must be unguessable: 128 or more bits from a CSPRNG, with the session data kept on the server; - a cookie holding data, such as a stateless session, must be signed with an HMAC (or encrypted with AEAD) using a server-side key, so the client cannot forge or modify it, and encrypted if the contents are confidential; - a timestamp or expiry inside the signed payload prevents indefinite reuse; - constant-time verification; - key rotation support.
Read full answerHide full answer
Applies toHTTP cookies (RFC 6265 and its successor drafts) (Python 3.12 example)
Code Example: An HMAC-Signed Cookie
import base64
import hashlib
import hmac
import json
import secrets
import time
SECRET = secrets.token_bytes(32) # server-side key, never sent to the browser
def sign(payload):
body = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode()
tag = hmac.new(SECRET, body.encode(), hashlib.sha256).hexdigest()
return f"{body}.{tag}"
def load(cookie, max_age=3600):
body, _, tag = cookie.rpartition(".")
expected = hmac.new(SECRET, body.encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(tag, expected):
return None # tampered or forged
payload = json.loads(base64.urlsafe_b64decode(body))
if time.time() - payload["iat"] > max_age:
return None # expired
return payload
cookie = sign({"uid": 42, "role": "user", "iat": int(time.time())})
print(load(cookie)["uid"]) # 42
# The browser can read the (base64) payload, but cannot change it without the key
body, tag = cookie.rsplit(".", 1)
forged_body = base64.urlsafe_b64encode(json.dumps({"uid": 42, "role": "admin", "iat": int(time.time())}).encode()).decode()
print(load(f"{forged_body}.{tag}")) # None
print("Set-Cookie: session=" + cookie[:20] + "...; Secure; HttpOnly; SameSite=Lax; Path=/; Max-Age=3600")
The payload is base64, not encrypted: anyone can read it, but changing role to admin invalidates the HMAC tag. If the payload must be secret, use authenticated encryption (AES-GCM) instead of a signature alone. Frameworks do this for you: Rails, Django and Flask signed or encrypted cookies, ASP.NET Data Protection, iron-session.
Cookie Attributes
Attribute
Effect
Recommended
Secure
Sent only over HTTPS
Always
HttpOnly
Not readable by JavaScript
Always for session cookies
SameSite
Strict: never sent cross-site; Lax: sent on top-level navigations; None: always (requires Secure)
Lax (default for many browsers) or Strict
__Host- prefix
Requires Secure, Path=/, and no Domain: cannot be set by subdomains
Use for session cookies
Max-Age / Expires
Lifetime
Short; idle and absolute timeouts on the server too
Missing Secure, which lets cookies leak over HTTP on a downgrade.
Long-lived stateless cookies that cannot be revoked.
Secrets inside a signed but unencrypted cookie.
Interview Tips
Separate browser attributes (Secure, HttpOnly, SameSite, __Host-) from cryptography (CSPRNG IDs, HMAC signing, AEAD encryption).
Explain the signed-versus-encrypted difference.
Mention session rotation, revocation, CSRF and key rotation.
45
Explain the principles behind homomorphic encryption and its potential applications.
KnownRevise
Homomorphic encryption (HE) lets someone compute on encrypted data without decrypting it. The encrypted result, once decrypted by the key owner, equals the result of the same computation on the plaintexts: Dec(f(Enc(a), Enc(b))) = f(a, b). A cloud server can therefore process sensitive data (sum salaries, score a medical model, run a query) while never seeing the data. There are three levels: - Partially homomorphic schemes support one operation without limit. RSA (textbook form) is multiplicatively homomorphic; Paillier is additively homomorphic. - Somewhat homomorphic schemes support both addition and multiplication, but only a limited number of operations, because each operation adds noise to the ciphertext. - Fully homomorphic encryption (FHE), first constructed by Craig Gentry in 2009, supports arbitrary computations. It uses bootstrapping to refresh noisy ciphertexts.
Modern FHE schemes (BFV, BGV, CKKS, TFHE/CGGI) are lattice-based, and therefore believed to be quantum-resistant. The main drawback is cost: FHE is still orders of magnitude slower than computing on plaintext, and ciphertexts are much larger, although libraries and hardware acceleration are improving quickly.
Read full answerHide full answer
Applies toPaillier, BFV/BGV, CKKS, TFHE (Python 3.12 toy example)
Code Example: Additive Homomorphism With Paillier
import math
import secrets
# Toy Paillier cryptosystem (additively homomorphic). Tiny primes for illustration only;
# real keys use a 2048-bit or larger modulus.
p, q = 1789, 1867
n = p * q
n2 = n * n
g = n + 1
lam = math.lcm(p - 1, q - 1)
mu = pow(lam, -1, n) # valid because g = n + 1
def encrypt(m):
while True:
r = secrets.randbelow(n - 1) + 1
if math.gcd(r, n) == 1:
return pow(g, m, n2) * pow(r, n, n2) % n2
def decrypt(c):
return (pow(c, lam, n2) - 1) // n * mu % n
salaries = [52_000, 61_500, 47_250]
encrypted = [encrypt(s) for s in salaries]
# A server multiplies the ciphertexts WITHOUT the private key; that adds the plaintexts
total = 1
for c in encrypted:
total = total * c % n2
print(decrypt(total)) # 160750 = 52000 + 61500 + 47250
doubled = pow(encrypted[0], 2, n2) # ciphertext ^ k multiplies the plaintext by k
print(decrypt(doubled)) # 104000
print(encrypt(5) != encrypt(5)) # True: encryption is randomised
Multiplying Paillier ciphertexts adds the hidden plaintexts, and raising a ciphertext to a power multiplies its plaintext by a constant. The server computes the payroll total without learning any salary. These toy primes are tiny; real deployments use 2048-bit or larger moduli and vetted libraries.
Types of Homomorphic Encryption
Type
Operations
Examples
Practicality
Partially homomorphic
Either addition or multiplication, unlimited
Paillier (+), ElGamal (×), textbook RSA (×)
Fast; e-voting tallies, private aggregation
Somewhat or levelled homomorphic
Both, up to a fixed depth
BFV, BGV, CKKS without bootstrapping
Practical for shallow circuits (statistics, simple ML inference)
Fully homomorphic
Arbitrary circuits (with bootstrapping)
TFHE (fast bootstrapping on bits and small integers), CKKS with bootstrapping
Libraries include Microsoft SEAL, OpenFHE, TFHE-rs and Concrete (Zama), and Lattigo.
Applications
Application
How HE helps
Private cloud computation
Outsource analytics on encrypted data
Healthcare and genomics
Run models on patient data across institutions without exposing records
Finance
Fraud scoring or credit models on encrypted customer data; cross-bank analytics
Private ML inference
The client sends encrypted features; the model runs on ciphertext
Private set intersection and contact discovery
Find common elements without revealing whole lists
Electronic voting
Additive tallying of encrypted votes (Paillier, ElGamal)
Advertising measurement
Aggregate conversions without sharing user-level data
Limitations
Performance: FHE operations are typically thousands to millions of times slower than plaintext operations, depending on the computation.
Ciphertext expansion: ciphertexts are much larger than plaintexts.
Programming model: computations must be written as circuits, without data-dependent branches.
Correctness without integrity: HE hides data but does not prove the server computed the right function; combine it with verifiable computation if needed.
Key management: whoever holds the secret key can decrypt every result.
HE Compared With Other Privacy Techniques
Technique
Trust model
Homomorphic encryption
One party computes on another’s encrypted data
Secure multi-party computation
Several parties compute jointly; no single party sees inputs
Define HE as computing on ciphertexts, where the decrypted result matches the plaintext computation.
Distinguish partial, somewhat and fully homomorphic schemes, noise and bootstrapping (Gentry, 2009).
Give applications and the performance trade-off, and compare it with MPC and enclaves.
46
What is zero-knowledge proof, and how does it maintain privacy?
KnownRevise
A zero-knowledge proof (ZKP) lets a prover convince a verifier that a statement is true, such as “I know the password”, “I am over 18” or “this transaction is valid”, without revealing anything beyond the fact that it is true. A ZKP must have three properties: - Completeness: an honest prover with a true statement convinces the verifier. - Soundness: a cheating prover with a false statement fails, except with negligible probability. - Zero knowledge: the verifier learns nothing else. Formally, everything the verifier sees could have been simulated without the secret.
Privacy follows from the zero-knowledge property: the secret (a key, a birth date, account balances) is never disclosed. The proof only shows that the prover knows it, or that it satisfies a rule. Classic interactive proofs, such as Schnorr identification, use a commitment, a random challenge and a response. The Fiat-Shamir transform makes them non-interactive by deriving the challenge from a hash. Modern zk-SNARKs (Groth16, PLONK) and zk-STARKs prove arbitrary computations with short proofs. They power private cryptocurrencies (Zcash), zk-rollups that scale Ethereum, anonymous credentials, and privacy-preserving identity checks.
Read full answerHide full answer
Applies toSchnorr protocols, zk-SNARKs and zk-STARKs (Python 3.12 toy example)
Code Example: Schnorr Identification
import secrets
# Schnorr identification: prove knowledge of x where y = g^x mod p, without revealing x.
# Toy group: safe prime p = 2q + 1; g = 4 generates the subgroup of prime order q. Real systems use
# elliptic curves or 2048+ bit groups, and the non-interactive Fiat-Shamir version.
q = 1_000_000_289 # prime
p = 2 * q + 1 # 2000000579, also prime (a safe prime)
g = 4 # a square, so it lies in the order-q subgroup
x = secrets.randbelow(q) # prover's secret
y = pow(g, x, p) # public key
def run_protocol(knows_secret):
r = secrets.randbelow(q)
t = pow(g, r, p) # 1. commitment
c = secrets.randbelow(q) # 2. verifier's random challenge
if knows_secret:
s = (r + c * x) % q # 3. response uses the secret
else:
s = secrets.randbelow(q) # a cheater can only guess
return pow(g, s, p) == t * pow(y, c, p) % p # 4. check g^s == t * y^c
print(all(run_protocol(True) for _ in range(20))) # True: honest prover always passes
print(any(run_protocol(False) for _ in range(20))) # False: cheater fails (except with tiny probability)
The prover shows they know x such that y = gˣ without sending x. The response s = r + c·x is masked by the random r, so it reveals nothing about x. Yet answering a random challenge correctly is only possible with x. A cheater passes a round only by guessing the challenge, which happens with negligible probability. The same idea underlies Schnorr signatures (Fiat-Shamir: the challenge c = H(t, message)).
The Three Properties
Property
Meaning
In the Schnorr example
Completeness
Honest provers succeed
gˢ = g^(r + cx) = t·yᶜ always holds
Soundness
Cheaters fail
Without x, answering two different challenges for the same t is impossible (doing so would reveal x)
Zero knowledge
Nothing else leaks
Valid (t, c, s) transcripts can be simulated by choosing s and c first and computing t
Very short proofs, fast verification; some need a trusted setup
Zcash, zk-rollups, private identity
zk-STARKs
No trusted setup; hash-based (post-quantum plausible); larger proofs
StarkNet, scalable computation proofs
Bulletproofs
No trusted setup; good for range proofs
Monero confidential amounts
Applications
Application
Statement proved without revealing the secret
Private payments (Zcash)
“This transaction spends coins I own and balances”, without showing amounts or addresses
zk-rollups
“These thousands of transactions were executed correctly” (scaling, not only privacy)
Age or credential checks
“I am over 18” from a signed credential, without revealing the birth date
Password authentication
Prove knowledge of a password (OPAQUE and other PAKEs) without sending it
Proof of reserves
An exchange proves its assets cover liabilities without revealing customer balances
Anonymous voting
“I am an eligible voter and voted once”, without revealing who
Limitations
Prover cost: generating SNARK or STARK proofs for large computations is expensive.
Trusted setups for some SNARKs: if the setup secret leaks, proofs can be forged.
Circuit bugs: an incorrectly written statement proves the wrong thing.
Metadata (timing, network) can still reveal information.
Interview Tips
Define ZKP with completeness, soundness and zero knowledge.
Walk through commitment → challenge → response (Schnorr), and Fiat-Shamir.
Give applications: Zcash, zk-rollups, age proofs, PAKEs; mention SNARKs versus STARKs.
47
Describe the concept of secure multi-party computation.
KnownRevise
Secure multi-party computation (MPC) lets several parties jointly compute a function of their private inputs while revealing only the output: no party learns another’s input, even though they compute together without a trusted third party. A classic example is Yao’s millionaires’ problem (1982): two people learn who is richer without revealing their wealth. MPC protocols use techniques such as: - secret sharing: each input is split into random shares handed to different parties; any subset below a threshold learns nothing, but computations on shares produce shares of the result; - garbled circuits (Yao): one party encrypts a boolean circuit, the other evaluates it with oblivious transfer for its inputs; - homomorphic encryption components.
Security is defined against semi-honest adversaries (they follow the protocol but try to learn more) or malicious ones (they may deviate), and against a threshold of corrupted parties. Applications include threshold signatures and MPC crypto wallets, private set intersection, privacy-preserving analytics across organisations (fraud detection between banks, salary-gap studies), and auctions.
Code Example: Private Sum With Additive Secret Sharing
import secrets
MOD = 2 ** 61 - 1 # all arithmetic is modulo a large prime
def share(value, parties=3):
shares = [secrets.randbelow(MOD) for _ in range(parties - 1)]
shares.append((value - sum(shares)) % MOD) # shares add up to the value; any subset looks random
return shares
salaries = {"alice": 82_000, "bob": 67_500, "carol": 91_250}
# Each person splits their salary into 3 random shares and gives one share to each party
dealt = {name: share(s) for name, s in salaries.items()}
# Party i adds up the shares it received: it sees only random-looking numbers
partial_sums = [sum(dealt[name][i] for name in salaries) % MOD for i in range(3)]
# Publishing only the partial sums reveals the total, and nothing about individual salaries
total = sum(partial_sums) % MOD
print(total, total / len(salaries)) # 240750 80250.0
print(dealt["alice"][0] != salaries["alice"]) # True: a single share is just noise
Each salary is split into three random shares that sum to it modulo a prime. Each party sees one share of every salary, which looks like random noise, adds them up and publishes only its partial sum. Combining the partial sums gives the total, and nothing more. This is secure against semi-honest parties as long as not all three collude. Real protocols add multiplication (Beaver triples) and checks against malicious behaviour.
Main Techniques
Technique
Idea
Strengths
Additive or Shamir secret sharing (GMW, BGW, SPDZ)
Inputs split into shares; additions are local; multiplications need interaction
Efficient arithmetic; many parties
Garbled circuits (Yao)
Encrypted truth tables evaluated gate by gate
Constant rounds; good for two parties and comparisons
Oblivious transfer
Receiver gets one of two messages; sender doesn’t learn which
Building block for garbled circuits and private set intersection
Homomorphic encryption hybrids
Compute on encrypted shares
Fewer communication rounds
Security Models
Model
Adversary
Cost
Semi-honest (honest-but-curious)
Follows the protocol, tries to learn more
Cheaper
Malicious
May deviate arbitrarily
More expensive (commitments, MACs on shares, zero-knowledge proofs)
Honest majority
Fewer than half the parties corrupted
Allows efficient information-theoretic protocols
Dishonest majority
Up to all but one corrupted
Needs heavier cryptography
Applications
Application
What stays private
MPC wallets and threshold signatures (ECDSA, EdDSA, FROST)
The full private key never exists in one place
Private set intersection
Contact discovery, ad conversion matching without sharing lists
Cross-bank fraud and anti-money-laundering analytics
Each bank’s customer data
Gender pay-gap studies (for example the Boston Women’s Workforce Council)
Individual companies’ salaries
Sealed-bid auctions
Bids other than the winning price
Federated machine learning with secure aggregation
Individual model updates
Trade-Offs
Communication and latency: parties exchange many messages; network performance dominates.
Complexity: protocols are subtle; use established frameworks (MP-SPDZ, MOTION, EMP-toolkit) and audited threshold signature libraries.
Output leakage: the result itself may reveal inputs (the sum of two salaries reveals the other if you know yours); combine with differential privacy or output limits.
Collusion assumptions must match reality.
MPC Compared With Related Techniques
Technique
Who computes
Trust
MPC
All parties together
Fewer than the threshold collude
Homomorphic encryption
One server on encrypted data
Key holder
Trusted execution environments
One machine’s secure enclave
Hardware vendor
Trusted third party
One party sees everything
That party
Interview Tips
Define MPC as joint computation where only the output is revealed, with no trusted third party.
Explain secret sharing (with the sum example), garbled circuits and oblivious transfer.
Cover semi-honest versus malicious models, and applications such as MPC wallets and private set intersection.
48
Explain the purpose of post-quantum cryptography.
KnownRevise
Post-quantum cryptography (PQC) is classical cryptography, running on ordinary computers, that is designed to stay secure even against attackers with large quantum computers. Its purpose is to replace the public-key algorithms that quantum computers would break. Shor’s algorithm solves integer factoring and discrete logarithms efficiently, so RSA, Diffie-Hellman, ECDH, ECDSA and EdDSA, which protect almost all key exchange, digital signatures and certificates today, would fall. Symmetric cryptography is only weakened by Grover’s algorithm (a square-root speed-up), so AES-256 and SHA-2/SHA-3 remain fine. PQC relies on problems believed hard even for quantum computers: lattices, hash functions, codes and others. NIST published the first standards in August 2024: - ML-KEM (FIPS 203, formerly Kyber) for key establishment; - ML-DSA (FIPS 204, formerly Dilithium) and SLH-DSA (FIPS 205, formerly SPHINCS+) for signatures; - more to come: FN-DSA (Falcon) and HQC as a backup KEM.
The urgency comes from “harvest now, decrypt later”: encrypted traffic recorded today could be decrypted once quantum computers exist. Hybrid key exchange such as X25519 + ML-KEM is already deployed in major browsers, Cloudflare, Signal and OpenSSH.
Compare with X25519 (32-byte keys) and Ed25519 (64-byte signatures): PQC keys and signatures are much larger, which affects TLS handshakes, certificates and constrained devices.
Hybrid Deployment
TLS 1.3 key share "X25519MLKEM768":
shared_secret = KDF( X25519 shared secret || ML-KEM-768 shared secret )
-> secure if EITHER algorithm holds: protects against quantum attacks AND against
undiscovered flaws in the newer ML-KEM
Why Start Migrating Now
Reason
Detail
Harvest now, decrypt later
Data needing secrecy for 10+ years is already exposed if recorded
Plan PKI and signature migration as standards, HSMs and CA support mature.
Test performance with larger keys and handshakes.
Pitfalls
Waiting for a quantum computer before acting.
Confusing PQC with quantum key distribution (QKD needs special hardware).
Switching to PQC-only too early without hybrids.
Ignoring size impacts on MTU, certificates and IoT.
Interview Tips
State the purpose: replace public-key algorithms broken by Shor’s algorithm; symmetric crypto mostly survives.
Name ML-KEM, ML-DSA and SLH-DSA (2024), and the lattice and hash foundations.
Explain harvest-now-decrypt-later, hybrids and crypto agility.
49
What is the NIST, and what role does it play in cryptography?
KnownRevise
The National Institute of Standards and Technology (NIST) is a US federal agency within the Department of Commerce that develops measurement science, standards and guidelines. In cryptography it is one of the world’s most influential bodies. Its roles: - Standardising algorithms in FIPS (Federal Information Processing Standards): AES (FIPS 197), SHA-2 and SHA-3 (FIPS 180-4, 202), digital signatures (FIPS 186-5), and the 2024 post-quantum standards ML-KEM, ML-DSA and SLH-DSA (FIPS 203–205). - Publishing guidance in the SP 800 series: modes of operation (SP 800-38), random number generation (SP 800-90), key management (SP 800-57), key derivation (SP 800-108, SP 800-56), transitions and deprecations (SP 800-131A), and digital identity (SP 800-63). - Running open public competitions, which built global trust: AES (1997–2001), SHA-3 (2007–2012) and post-quantum cryptography (2016–2024). - Validating implementations: together with Canada’s Cyber Centre, it runs the Cryptographic Module Validation Program (CMVP) for FIPS 140-3 and the algorithm validation program (CAVP/ACVP).
US federal agencies must use FIPS-validated cryptography, and many regulated industries and international organisations follow NIST too.
Read full answerHide full answer
Applies toNIST FIPS and SP 800 publications, CMVP, PQC standardisation
Key NIST Cryptographic Standards
Publication
Content
FIPS 197
AES
FIPS 180-4, FIPS 202
SHA-2; SHA-3 and SHAKE
FIPS 186-5
Digital signatures: RSA, ECDSA, EdDSA (Ed25519 added in 2023)
Open competitions with public analysis by researchers worldwide are why NIST algorithms are widely trusted.
Controversy: Dual_EC_DRBG
NIST standardised the Dual_EC_DRBG random number generator in SP 800-90A (2006). After the 2013 Snowden disclosures suggested an NSA backdoor, NIST withdrew it (2014), reviewed its processes, and committed to more transparency and independence. The episode is why the community values open processes, explainable constants (“nothing-up-my-sleeve” numbers) and independent review.
Why It Matters to Engineers
Compliance: US government work (FedRAMP, FISMA), and many contracts and regulated sectors, require FIPS-validated modules and NIST-approved algorithms.
Defaults: NIST deprecation schedules (for example, SHA-1 and 3DES, and RSA and ECC by 2030–2035 under NIST IR 8547) guide upgrades.
Global influence: other standards bodies (ISO, IETF) and other countries often align with NIST algorithms.
Pitfalls
Assuming “NIST-approved” means “any usage is safe”: misuse (nonce reuse, ECB) breaks approved algorithms too.
Confusing “uses AES” with “FIPS-validated”: validation applies to specific module versions and configurations.
Ignoring transition deadlines in SP 800-131A.
Interview Tips
Describe NIST as the US standards body behind FIPS and SP 800 crypto standards.
Mention the AES, SHA-3 and PQC competitions, and FIPS 140-3 validation.
Note the Dual_EC_DRBG episode and why open processes matter.
50
How do cryptographic modules get validated (e.g., FIPS 140)?
KnownRevise
Cryptographic modules (the hardware, software or firmware that implements cryptography, such as an HSM, OpenSSL’s FIPS provider, a cloud KMS or a smart card) are validated in the US and Canada through the Cryptographic Module Validation Program (CMVP), run jointly by NIST and the Canadian Centre for Cyber Security, against FIPS 140-3. FIPS 140-3 replaced FIPS 140-2 and is aligned with ISO/IEC 19790 and 24759. FIPS 140-2 validations reached their sunset in September 2026 and moved to the historical list. The process: 1. Algorithm testing through the Cryptographic Algorithm Validation Program (CAVP), using the automated ACVP test service. Each approved algorithm (AES-GCM, SHA-256, ECDSA, DRBG and so on) gets its own certificate. 2. The vendor defines the module boundary, the security level (1–4) and a security policy. 3. An accredited independent laboratory (NVLAP-accredited) tests the module against every FIPS 140-3 requirement area: interfaces, roles and authentication, self-tests, key management, physical security, non-invasive attack mitigation, documentation and lifecycle. 4. The lab submits its report; CMVP reviews it, often through a long queue with comments and fixes. 5. A validation certificate is published listing the exact module version, operating environments and approved mode.
Changes need revalidation, and only the validated version, used in its approved mode, counts as “FIPS-validated”.
Read full answerHide full answer
Applies toFIPS 140-3, CMVP, CAVP/ACVP
Security Levels
Level
Main requirements
Typical modules
1
Approved algorithms; production-grade components; no physical security requirements
Software libraries (OpenSSL FIPS provider, BoringCrypto, Windows CNG)
Data, control, status; trusted channels at higher levels
Roles, services, authentication
Crypto officer and user roles
Software and firmware security
Integrity tests (HMAC or signature on load)
Operational environment
OS requirements for software modules
Physical security
Tamper evidence, resistance and response
Non-invasive security
Side-channel mitigations (testing specifics are still evolving)
Sensitive security parameter management
Key generation (approved DRBGs and entropy, SP 800-90B), storage, zeroisation
Self-tests
Pre-operational and conditional tests (known-answer tests, pairwise consistency)
Lifecycle assurance
Configuration management, delivery, guidance
Using Validated Modules in Practice
# OpenSSL 3: check whether the FIPS provider is installed and active
openssl list -providers
# A FIPS-enabled build lists "fips" with status: active
Cloud providers offer FIPS endpoints (for example AWS *-fips endpoints), FIPS-validated KMS and HSMs. Operating systems such as RHEL and Ubuntu Pro have FIPS modes that restrict libraries to validated modules.
Related Programmes
Programme
Scope
CAVP/ACVP
Correctness of individual algorithm implementations
CMVP (FIPS 140-3)
Whole cryptographic modules
Common Criteria (ISO/IEC 15408)
Broader product security evaluation against protection profiles
PCI PTS HSM
Payment HSM requirements
National schemes
For example the German BSI, French ANSSI certifications
Pitfalls
Claiming “FIPS compliant” when using an unvalidated build or non-approved algorithms.
Running outside the validated environment or mode (other OS, non-approved algorithms such as MD5 for security, or using ChaCha20 in places that require approved algorithms).
Long validation timelines: plan ahead, and track module versions on the “Modules In Process” list.
Using deprecated FIPS 140-2 certificates for new procurement after the sunset.
Interview Tips
Explain CAVP algorithm testing, then lab testing → CMVP review → certificate for the module.
Describe the four security levels and key requirement areas.
Stress exact versions, approved mode, and the FIPS 140-2 to 140-3 transition.
51
Explain the importance and usage of the Common Criteria for IT Security Evaluation.
KnownRevise
The Common Criteria (CC), formally ISO/IEC 15408, with the evaluation methodology in ISO/IEC 18045 (the CEM), is an international framework for specifying, evaluating and certifying the security of IT products: firewalls, operating systems, smart cards, HSMs, network devices, databases and more. Instead of one fixed checklist, it provides a common language: - Protection Profiles (PPs), often collaborative PPs (cPPs), define the security requirements for a class of products, such as “network devices” or “full disk encryption”. - A vendor’s Security Target (ST) states exactly what their Target of Evaluation (TOE) claims: its security functional requirements (SFRs) and the assurance requirements (SARs), often packaged as an Evaluation Assurance Level (EAL1–EAL7). - An accredited laboratory evaluates the product against the ST: design documentation, testing, vulnerability analysis, lifecycle. - A national certification body issues the certificate.
Its importance: procurement requirements for government and defence (for example US NIAP, which requires NIAP-approved PPs for national security systems), mutual recognition across countries under the CCRA, and the EU’s EUCC cybersecurity certification scheme. It also offers independent, comparable assurance for buyers. Cryptographic functions inside a CC-evaluated product usually also rely on FIPS 140-3 validated modules and algorithm testing.
A higher EAL means more rigorous evaluation of the claims, not necessarily more security features. Two EAL4 products can have very different security functionality.
The Evaluation Process
1. Vendor selects a PP (or writes an ST) and a lab; defines the TOE and evaluated configuration
2. Lab evaluates: ST review, design documentation, guidance, lifecycle, functional testing,
independent vulnerability analysis and penetration testing
3. Certification body oversees the evaluation and issues the certificate + certification report
4. Product listed on the Common Criteria portal (or the NIAP Product Compliant List)
5. Maintenance or re-evaluation for new versions (assurance continuity)
Cryptography in Common Criteria
PPs specify cryptographic SFRs (class FCS): key generation, key establishment, encryption, hashing, random bit generation, with allowed algorithms and key sizes.
Many schemes require algorithm validation (CAVP) and accept or require FIPS 140-3 module validation for the crypto inside.
Smart card and secure element evaluations (EAL5+ or EAL6+) focus heavily on side-channel and fault-attack resistance.
Benefits and Criticisms
Benefits
Criticisms
Independent, standardised assurance
Expensive and slow (months to years)
Required for many government purchases
Certified configurations may differ from real deployments
Mutual recognition across countries
Certificate applies to a specific version; updates need maintenance
Encourages documented, secure development
Assurance level can be misread as feature strength
Pitfalls
Treating a certificate as proof of no vulnerabilities.
Deploying outside the evaluated configuration (other settings, modules or versions).
Ignoring the Security Target, which states what was actually evaluated.
Interview Tips
Define CC as ISO/IEC 15408, with the PP / ST / TOE concepts.
Explain EALs as levels of assurance rigour, not features.
Mention CCRA mutual recognition, NIAP and EUCC, and the relationship with FIPS 140-3.
52
Describe the purpose of the TLS protocol and its predecessor SSL.
KnownRevise
Transport Layer Security (TLS) secures communication between two applications over a network. It provides: - confidentiality: encryption; - integrity: tampering is detected; - authentication: normally of the server, optionally of the client, via X.509 certificates.
It sits between TCP (or, for QUIC, UDP) and application protocols, and secures HTTPS, SMTP/IMAP email, database connections, gRPC, VPNs and API traffic. SSL (Secure Sockets Layer) was its predecessor, created by Netscape: SSL 2.0 (1995) and SSL 3.0 (1996). Both are broken and prohibited: SSL 2.0 had fundamental design flaws, and SSL 3.0 fell to the POODLE attack (2014). The IETF standardised TLS 1.0 (1999) as an evolution of SSL 3.0, followed by TLS 1.1 (2006), TLS 1.2 (2008) and TLS 1.3 (2018). TLS 1.0 and 1.1 are deprecated (RFC 8996, 2021). Today’s minimum is TLS 1.2 with AEAD cipher suites, and TLS 1.3 is preferred: a faster one-round-trip handshake, mandatory forward secrecy, encrypted certificates, and only modern algorithms. “SSL certificate” survives as a legacy name for TLS certificates.
The cipher list applies to TLS 1.2; TLS 1.3 suites are secure by default. Mozilla’s SSL Configuration Generator produces up-to-date settings for common servers.
Pitfalls
Leaving SSL 3.0, TLS 1.0 or 1.1 enabled “for compatibility”.
Allowing CBC, RC4, 3DES or RSA key-exchange suites in TLS 1.2.
Disabling certificate validation in clients.
Terminating TLS at the edge and sending plain text over untrusted internal networks.
Interview Tips
State TLS’s purpose: confidentiality, integrity and authentication for application traffic.
Explain that SSL was the predecessor (Netscape) and is broken (POODLE, DROWN).
Highlight TLS 1.3 improvements and the TLS 1.2 minimum.
53
What is the S/MIME standard, and what is it used for?
KnownRevise
S/MIME (Secure/Multipurpose Internet Mail Extensions) is the IETF standard for signing and encrypting email with X.509 certificates. The current version is S/MIME 4.0 (RFC 8551), built on the Cryptographic Message Syntax (CMS, RFC 5652). It provides: - digital signatures: proof of sender authenticity and message integrity (and support for non-repudiation), checked by recipients with the sender’s certificate chain; - encryption: confidentiality of the message body and attachments end to end, from the sender’s client to the recipient’s client, not just between mail servers. It uses a random content-encryption key (AES-GCM, or AES-CBC for compatibility) wrapped for each recipient’s public key (RSA-OAEP or ECDH).
It is built into Outlook, Apple Mail, Thunderbird and many mobile and enterprise clients. It is common in enterprises, government and defence (for example US government PIV/CAC cards), and in regulated industries such as healthcare and finance, wherever an organisation has PKI to issue certificates. Its main hurdles are certificate distribution and key management. Recipients’ certificates are needed to encrypt, and lost private keys mean lost mail, so organisations often escrow encryption keys. S/MIME does not encrypt headers such as the subject line by default.
Signing (sender):
digest = SHA-256(message); signature = Sign(sender private key, signed attributes incl. digest)
attach sender certificate chain -> recipient verifies chain + signature
Encryption (sender):
CEK = random AES key; ciphertext = AES-GCM(CEK, MIME body + attachments)
for each recipient (and the sender, to read it in Sent items):
wrapped_CEK_i = RSA-OAEP(recipient_i public key, CEK) or ECDH key agreement
recipient decrypts wrapped_CEK with its private key -> CEK -> message
Messages are usually signed, then encrypted, so the signature is protected too.
Example With OpenSSL
# Sign (clear-signed, so non-S/MIME clients can still read the text)
openssl cms -sign -in note.txt -signer alice.crt -inkey alice.key -out signed.eml
# Encrypt for Bob with AES-256-GCM
openssl cms -encrypt -aes-256-gcm -in note.txt -out encrypted.eml bob.crt
# Bob decrypts and the signature is verified
openssl cms -decrypt -in encrypted.eml -recip bob.crt -inkey bob.key -out note.txt
openssl cms -verify -in signed.eml -CAfile ca-bundle.pem -out verified.txt
S/MIME Versus Other Email Protections
Mechanism
Protects
Scope
S/MIME
Message content: signature and encryption
End to end (client to client)
OpenPGP
Same goals, web-of-trust or other key models
End to end
STARTTLS, MTA-STS, DANE
The connection between mail servers
Hop by hop; servers see plain text
SPF, DKIM, DMARC
Domain-level sender authentication
Server to server; not user-level signatures
Provider “confidential” modes
Access control on a portal
Provider can read the content
Certificates and Key Management
Topic
Practice
Issuance
Public CAs follow the CA/Browser Forum S/MIME Baseline Requirements (in force since 2023); enterprises often use private CAs
Separate keys
Separate signing and encryption keys and certificates (escrow only the encryption key)
Storage
Smart cards, PIV/CAC, OS key stores, HSM-backed services
Distribution
Directories (LDAP, Global Address List); certificates attached to signed emails
Renewal and recovery
Keep old decryption keys to read archived mail
Limitations
Headers are not encrypted by default: subject, sender, recipients and timestamps leak.
Adoption barriers: every recipient needs a certificate, and webmail support varies.
Implementation flaws: the 2018 EFAIL attacks exploited malleable CBC encryption and HTML rendering in clients; AES-GCM in S/MIME 4.0 and careful clients mitigate it.
Server-side features (search, spam filtering, archiving) cannot see encrypted content.
Pitfalls
Losing old private keys, which makes archived encrypted mail unreadable.
Using one key for signing and encryption.
Assuming the subject line is protected.
Legacy algorithms (3DES, SHA-1) in old configurations.
Interview Tips
Define S/MIME as certificate-based email signing and encryption, built on CMS.
Explain hybrid encryption per recipient and sign-then-encrypt.
Contrast it with TLS for transport and DKIM, and mention key management and EFAIL.
54
When should you use hardware-based cryptographic modules such as HSMs?
KnownRevise
A hardware security module (HSM) is tamper-resistant hardware that generates, stores and uses cryptographic keys inside a protected boundary: private keys are never exported in plaintext. Applications send requests (“sign this”, “decrypt this”, “wrap this key”) through APIs such as PKCS#11, JCE or KMIP. Use an HSM, or an HSM-backed cloud service, when key compromise would be catastrophic or hard to recover from, when regulations or standards require it, or when you need strong, auditable control over key use: - root and issuing CA keys in a PKI; - code-signing and firmware-signing keys; - payment keys (PIN processing and card issuing require PCI-certified payment HSMs); - master keys that protect many data keys (envelope encryption); - TLS private keys for very high-value services; - blockchain custody; - document-signing and qualified electronic signatures (eIDAS); - workloads needing FIPS 140-3 Level 3 or Common Criteria certification.
For most applications, a cloud KMS (itself backed by HSMs) gives most of the benefit with far less operational effort. Dedicated or single-tenant HSMs (AWS CloudHSM, Azure Managed or Dedicated HSM, Google Cloud HSM, on-premises Thales Luna or Entrust nShield) are for when you need exclusive control, specific APIs or compliance.
# List keys on a token (SoftHSM shown for testing; real HSMs ship their own PKCS#11 library)
pkcs11-tool --module /usr/lib/softhsm/libsofthsm2.so --login --list-objects
# Sign with a non-exportable key: the private key never leaves the module
pkcs11-tool --module /usr/lib/softhsm/libsofthsm2.so --login --sign \
--mechanism ECDSA-SHA256 --id 01 --input-file artifact.bin --output-file artifact.sig
SoftHSM is a software emulator for development and testing only.
Operational Considerations
High availability: clusters across zones; plan for HSM failure and network latency.
Backup: HSM-encrypted backups to other HSMs of the same vendor; test restores.
Key ceremonies: documented, witnessed generation of root keys.
Access: strong authentication for crypto officers; separation of duties.
Monitoring: log and alert on key usage anomalies.
Pitfalls
Assuming the HSM fixes application security: if an attacker controls the application, they can ask the HSM to sign or decrypt. Restrict and monitor key usage.
Exporting keys “for convenience”, which defeats the purpose.
No backup, so an HSM failure means permanent key loss.
Over-engineering: dedicated HSMs for low-risk secrets.
Interview Tips
Define an HSM as tamper-resistant hardware where keys are used but never leave.
Give use cases: CA roots, code signing, payments, master keys, compliance.
Compare with cloud KMS, and note HA, backup, quorum and that compromised apps can still misuse keys.
55
What are the best practices for managing cryptographic keys within an enterprise?
KnownRevise
Enterprise key management covers the whole key lifecycle under clear policy, ownership and auditing. The best practices: - Inventory every key and certificate: where it lives, what it protects, who owns it, its algorithm and expiry. - Generate keys with approved algorithms and CSPRNGs inside KMS or HSMs. - Store them so they are never in plaintext in code, configuration, images or tickets: use KMS, HSMs, secret managers or TPMs, and envelope encryption. - Limit use with least privilege, one purpose per key, and separation of duties (M-of-N for critical keys). - Distribute keys securely and automate rotation on schedules and after incidents. - Revoke and destroy keys reliably, with backup and recovery for encryption keys (not signing keys). - Log and monitor every use. - Plan for crypto agility, including the post-quantum transition.
Standards to follow include NIST SP 800-57 (key management), SP 800-130/152 (key management system design), ISO/IEC 11770, PCI DSS requirements 3 and 4 for payment data, and cloud providers’ KMS guidance.