Cryptographic hash functions and SHA
Clear, exam-focused notes on cryptographic hash functions (definitions, properties, Merkle–Damgård, SHA family, birthday bound), with formulas, worked examples (SHA-256 padding for "abc" and a toy hash trace), common mistakes and exam guidance.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Cryptographic hash functions are used everywhere an engineer needs a compact, fixed-size fingerprint of data: for message integrity (checksums, HMAC), as inputs to digital signatures, in blockchain linking, and for password storage (when combined with salt and slow hashing). Understanding their properties and limits prevents misuse (for example, using fast general-purpose hashes where slow password hashing is needed) and helps you answer exam questions on constructions such as Merkle–Damgård and the SHA family.
Key ideas
Required properties (exact definitions expected in exams):
- Preimage resistance (one-wayness): Given a hash value y, it is computationally infeasible to find any x such that H(x) = y. Assumption: attacker is bounded to feasible computational resources (no magical break of underlying primitives).
- Second-preimage resistance: Given a specific input x1, it is computationally infeasible to find x2 ≠ x1 with H(x2) = H(x1).
- Collision resistance: It is computationally infeasible to find any pair x1 ≠ x2 such that H(x1) = H(x2). (Collision resistance ⇒ second-preimage resistance, but not conversely in all formal settings.)
Deterministic and fixed-length output are functional properties; a hash is not encryption (no key, not reversible by design) and does not provide confidentiality.
Practical implication of lengths: For an n-bit hash, brute-force preimage resistance cost is about 2^n work; collision resistance costs about 2^(n/2) work by the birthday paradox. The exam will often ask you to derive the 2^(n/2) estimate—see derivation below.
Construction patterns:
- Merkle–Damgård construction: a way to convert a compression function f that maps fixed-size chaining value and block into a new chaining value into a hash for arbitrary-length messages. Precisely: split message into blocks M1,...,Mt (after padding); start with an initialisation vector IV; compute H0 = IV and for i = 1..t, Hi = f(Hi-1, Mi); output Ht (or sometimes a finalisation function applied to Ht). This construction preserves collision resistance of f (if f is collision-resistant and MD-strengthening is used, i.e., padding that encodes the message length).
- What to draw: a left-to-right block diagram. Draw IV box -> arrow to f with M1 -> output H1 -> arrow to next f with M2, ... until Mt produces Ht -> final output. Label each f box "compression f(Hi-1, Mi) -> Hi" and show the message blocks below the f boxes.
- Merkle tree: for many-message hashing (not discussed in-depth here) — tree of compressions to allow efficient proofs.
- Merkle–Damgård construction: a way to convert a compression function f that maps fixed-size chaining value and block into a new chaining value into a hash for arbitrary-length messages. Precisely: split message into blocks M1,...,Mt (after padding); start with an initialisation vector IV; compute H0 = IV and for i = 1..t, Hi = f(Hi-1, Mi); output Ht (or sometimes a finalisation function applied to Ht). This construction preserves collision resistance of f (if f is collision-resistant and MD-strengthening is used, i.e., padding that encodes the message length).
SHA family overview (safe short statements):
- SHA-0: original (now obsolete).
- SHA-1: 160-bit digest; weaknesses: theoretical collision attacks and practical collisions found — do not use for collision-resistance purposes.
- SHA-2: family including SHA-224, SHA-256, SHA-384, SHA-512. SHA-256 is commonly used and currently considered secure for many uses (collision resistance ~ 2^128 work). SHA-224/256 use 512-bit message blocks and 32-bit words with a 64-bit length field in padding; SHA-384/512/512-224/512-256 use 1024-bit message blocks and 64-bit words with a 128-bit length field in padding.
- SHA-3: different internal structure (sponge construction); standardized later as alternative with different security assumptions.
Padding rule (Merkle–Damgård type hashes): For SHA-1 and the 32-bit-word SHA-2 variants (SHA-224/256), pad by appending a 1 bit, then the minimum number of 0 bits so that the length is ≡ 448 (mod 512), then append the 64-bit big-endian length of the original message (mod 2^64). For the 64-bit-word SHA-2 variants (SHA-384/512/512-224/512-256), pad to ≡ 896 (mod 1024) and append a 128-bit big-endian length (mod 2^128). This MD-strengthening makes padding unambiguous and is required for the standard security proofs.
Birthday paradox (sketch & exam-style derivation): for a random function mapping a large domain to n-bit outputs, the probability of finding a collision among k random outputs grows like ≈ k^2/(2^{n+1}). Setting this probability ~ 1 gives k ≈ 2^{n/2}. Thus collision security is roughly 2^{n/2}.
- Derivation steps (common exam derivation): consider choosing k outputs uniformly at random from 2^n values. Probability no collision ≈ product_{i=0 to k-1} (1 - i/2^n) ≈ exp(-k(k-1)/(2·2^n)). Setting exponent ≈ -1 gives k ≈ sqrt(2^{n+1}) ≈ 2^{n/2}.
Usage notes and pitfalls briefly:
- For message authentication use HMAC (hash-based message authentication code), not raw hash.
- For password storage use slow, memory-hard functions (bcrypt, scrypt, Argon2) with per-password salt; do not store raw hash(M) without salt.
- When you need collision resistance (e.g., digital signatures), avoid SHA-1.
Formulas
h = H(M) — h is the fixed-length digest (n bits) of message M; units: bits (length), applies to any hash function.
H0 = IV — initial chaining value for Merkle–Damgård; IV is specified by the hash standard (size: n-bit value; typically represented as a vector of word-sized constants, e.g., 8×32-bit for SHA-256 or 8×64-bit for SHA-512), used as start state for compression.
Hi = f(Hi-1, Mi) — compression step in Merkle–Damgård: Hi is the chaining value after processing message block Mi; Hi and Hi-1 are n-bit values; Mi is one message block (size depends on hash), applies when using Merkle–Damgård.
Work_preimage ≈ 2^n — brute-force work to find preimage for n-bit hash; unit: number of hash evaluations; applies when hash behaves like a random function.
Work_collision ≈ 2^{n/2} — estimated work to find any collision by birthday attack; unit: number of hash evaluations; derivation in Key ideas.
P(no collision after k samples) ≈ exp(-k(k-1)/(2·2^n)) — approximation from Poisson limit used in birthday derivation; applies when k << 2^{n}.
(Note: these formulas are complexity estimates, not physical SI units. Symbols: n = digest length (bits), k = number of sampled hashes, Hi = chaining value, Mi = i-th message block.)
Worked examples
Example 1 — Padding and final known digest (SHA-256) for small message "abc".
- Write the message bytes (ASCII): 'a' = 0x61, 'b' = 0x62, 'c' = 0x63. Total message length = 3 bytes = 24 bits.
- Apply SHA-256 padding rule: append bit '1' then smallest number of '0' bits so that length ≡ 448 (mod 512), then append 64-bit big-endian length = 24 (0x0000000000000018).
- Represent the single 512-bit block as 16 32-bit words W0..W15 (big-endian words): W0 = 0x61626380 W1..W13 = 0x00000000 (13 words of zeros) W14 = 0x00000000 (high 32 bits of length) W15 = 0x00000018 (low 32 bits = 24 decimal)
- SHA-256 initializes H0..H7 to standard constants, runs 64 rounds of the compression on this block and produces the final digest.
Final output (well-known test vector): SHA-256("abc") =
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad.
Bold final answer: ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad.
(Exam expectation: show padding steps and the single-block words; you are not normally required to compute all 64 rounds by hand — instead show correct padding and state the known digest or show the compression round equation.)
Example 2 — Toy Merkle–Damgård hash to illustrate steps and avalanche.
Define a tiny hash for teaching: digest size 8 bits, block size 8 bits, IV = 0x00. Compression function f(H, M) = (ROR(H xor M, 1) + M) mod 256, where ROR(x,1) is rotate-right on 8 bits.
Compute H for message consisting of two blocks: M1 = 0x12, M2 = 0x34.
Step 1: H0 = IV = 0x00. Step 2: H1 = f(H0, M1) = ROR(0x00 xor 0x12,1) + 0x12 = ROR(0x12,1) + 0x12.
- ROR(0x12 = 0001 0010) by 1 -> 0x09 (0000 1001).
- H1 = 0x09 + 0x12 = 0x1B. Step 3: H2 = f(H1, M2) = ROR(0x1B xor 0x34,1) + 0x34.
- 0x1B xor 0x34 = 0x2F (0010 1111). ROR(0x2F,1) -> 0x97 (1001 0111) because low bit moves to top.
- H2 = 0x97 + 0x34 = 0xCB (203 decimal mod 256). Final digest = H2 = 0xCB.
If you flip one bit of M1 (say M1 = 0x13 instead of 0x12), recompute and note H2 changes markedly (avalanche demonstration).
This toy calculation model answer shows step-by-step trace the exam might ask for when testing your understanding of chaining.
Common mistakes
- Saying collision-resistance implies preimage-resistance (not directly; collision resistance implies second-preimage resistance under some models but not simple implication to preimage-resistance).
- Forgetting to include the length field in Merkle–Damgård padding (causes ambiguous padding). Note: length-extension attacks exist even with correct MD padding; mitigate by using HMAC or a non–length-extensible construction (e.g., SHA-3 or designs with proper finalisation/Domain separation).
- Using SHA-256 as a password hash without salt and stretching: insecure practice (fast hash → vulnerable to brute force).
- Claiming SHA-1 is secure for collision resistance (it has known practical collisions).
- Trying to compute full 64 rounds of SHA-256 by hand in exam; instead, show padding and one round or cite known test vectors where allowed.
For your exam
Question types:
- Definitions (give precise definitions of preimage/second-preimage/collision resistance).
- Short notes (Merkle–Damgård, birthday paradox, SHA family differences, HMAC vs raw hash).
- Derivations (birthday paradox derivation leading to 2^(n/2)).
- Numericals/traces (compute padding for a short message, compute simple toy hash by hand, demonstrate avalanche on toy hash).
- Diagrams (draw Merkle–Damgård chaining or block diagram for padding and compression).
Full-marks answer components:
- For definitions: state the formal definition and the assumption about attacker resources.
- For derivations: show each approximation step (product → exponential approx), conclude with 2^(n/2) and explain meaning.
- For padding questions: show byte/bit representation and final padded block(s) explicitly.
- For algorithm traces: list initial state, each intermediate Hi, and the final digest; include units (bits) where relevant.
Quick check
- What property requires that given H(x) it is hard to find any x that hashes to H(x)?
- For a 256-bit hash, roughly how much work (in exponent) does a birthday attack need to find a collision?
- In Merkle–Damgård padding, how many bits are appended after the '1' bit before the 64-bit length field (mod 512)?
Answers: 1) Preimage resistance. 2) Approximately 2^128 hash evaluations (collision work ≈ 2^{n/2} so with n=256 gives 2^128). 3) For SHA-1/SHA-224/256: append the minimum number of '0' bits so that the length before the final 64-bit length field is ≡ 448 (mod 512). For SHA-384/512/512-224/512-256: pad so the length before the final 128-bit length field is ≡ 896 (mod 1024).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?