Tutorial 2.9: Hash Functions and Data Integrity

Table of Contents

Learning Objectives

After completing this tutorial, you should be able to:

Overview

Cryptographic hash functions are fundamental building blocks of modern cryptography. They serve as the "fingerprint" of data, producing a fixed-size digest that uniquely represents an input of arbitrary length. Hash functions are used for data integrity verification, password storage, digital signatures, message authentication, and blockchain technology.

Unlike encryption, hash functions are one-way—it is computationally infeasible to recover the input from the hash output. This one-way property makes them invaluable for security applications. The security of a hash function depends on three key properties: preimage resistance, second preimage resistance, and collision resistance.

In this tutorial, we explore the theory and practice of cryptographic hash functions. We begin by defining the essential properties and examining the design principles behind popular hash functions. We then survey the SHA family (SHA-1, SHA-2, SHA-3), discussing their structures, security strengths, and vulnerabilities. We examine other algorithms such as MD5 and BLAKE2, and we explore practical applications including password storage, file integrity, digital signatures, and blockchain.

We also analyze the security of hash functions, including the historical attacks on MD5 and SHA-1, the implications of collision attacks, and the importance of choosing appropriate hash algorithms for different applications. Finally, we discuss standards and recommendations for hash function usage in modern systems.

Relationship to the Tutorial Series

In Tutorials 2.1–2.8, we studied encryption, modes, and random number generation. This tutorial introduces a different class of cryptographic primitive—hash functions—which provide integrity rather than confidentiality. Tutorial 2.10 will cover Message Authentication Codes (MACs), which build on hash functions. Tutorials 2.11–2.15 will use hash functions in digital signatures and public-key infrastructure.

Introduction to Cryptographic Hash Functions

Cryptographic Hash Function
A cryptographic hash function H maps an input message M of arbitrary length to a fixed-size output h = H(M), called the hash value, digest, or fingerprint.

A cryptographic hash function must be:

┌─────────────────────────────────────────────────────────────────┐ │ HASH FUNCTION MODEL │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ Input (arbitrary length) Output (fixed length) │ │ ┌─────────────────────────┐ ┌─────────────────────────────┐ │ │ │ "Hello, world!" │ │ 5f4dcc3b5aa765d61d8327deb │ │ │ │ │ │ d882cf99b1a9e3b7bc2f7a │ │ │ │ ──► │ │ │ │ │ (1000 pages of text) │ │ (256-bit digest) │ │ │ │ │ │ │ │ │ │ (1 byte) │ │ (same length) │ │ │ └─────────────────────────┘ └─────────────────────────────┘ │ │ │ │ • One-way: cannot recover input from output │ │ • Collision-resistant: infeasible to find two inputs with │ │ same output │ └─────────────────────────────────────────────────────────────────┘

Figure 1: The hash function model.

Properties of Cryptographic Hash Functions

1. Preimage Resistance (One-Way Property)

Given a hash value h, it is computationally infeasible to find any input M such that H(M) = h.

Formal definition: For a randomly chosen hash value h, the probability that an attacker can find M such that H(M) = h is negligible.

Importance: This property ensures that an attacker cannot recover the original data from its hash. This is crucial for password storage—even if an attacker obtains the password hash, they cannot determine the password.

2. Second Preimage Resistance

Given an input M1, it is computationally infeasible to find a different input M2 such that H(M1) = H(M2).

Formal definition: For a randomly chosen M1, the probability of finding M2 ≠ M1 with H(M1) = H(M2) is negligible.

Importance: This prevents an attacker from substituting one document for another with the same hash. For example, in digital signatures, if an attacker can find a second preimage, they could forge a signature on a different document.

3. Collision Resistance

It is computationally infeasible to find any two distinct inputs M1 and M2 such that H(M1) = H(M2).

Formal definition: The probability that any attacker can find a collision is negligible.

Importance: Collision resistance is the strongest property. If collisions can be found, an attacker can create two documents with the same hash—one benign and one malicious—and have the signature on the benign document be valid for the malicious one.

Relationship Between Properties

Collision resistance implies second preimage resistance, but not vice versa. Preimage resistance is independent of the other two, though a function that is not collision-resistant may still be preimage-resistant.

Key Insight: The birthday paradox significantly affects collision resistance. For an n-bit hash, the expected number of hashes needed to find a collision is about 2n/2. This is why hash functions use larger output sizes (e.g., 256 bits) to provide 128 bits of collision resistance.

Additional Desirable Properties

Hash Function Design Principles

Merkle-Damgård Construction

The Merkle-Damgård construction is the most common design for hash functions, used in MD5, SHA-1, and SHA-2. It builds a hash function from a compression function (which processes fixed-size blocks) by applying it iteratively to the message, which is padded to a multiple of the block size.

Process:

  1. Padding: The message is padded to a multiple of the block size (e.g., 512 bits for SHA-256). The padding includes the length of the original message.
  2. Initialization: The hash function starts with an initial vector (IV) of fixed size.
  3. Iteration: For each block, the compression function takes the current state (from the previous block) and the current message block, producing a new state.
  4. Finalization: The final state is the hash value.
┌─────────────────────────────────────────────────────────────────┐ │ MERKLE-DAMGÅRD CONSTRUCTION │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ Message ──► Padding ──► M₁ ──► M₂ ──► ... ──► Mₙ │ │ │ │ IV ──► [Compress] ──► State₁ ──► [Compress] ──► ... ──► Hash │ │ M₁ M₂ │ │ │ │ • Compression function processes fixed-size blocks │ │ • Padding ensures message length is multiple of block size │ │ • Length included in padding to prevent length extension │ │ attacks (when used with proper finalization) │ └─────────────────────────────────────────────────────────────────┘

Figure 2: Merkle-Damgård construction.

Sponge Construction

The sponge construction is used in SHA-3. It operates on a state of fixed size (the "sponge") and uses two phases: absorption and squeezing.

The sponge construction provides flexibility: any output length can be produced by squeezing the appropriate number of bits.

┌─────────────────────────────────────────────────────────────────┐ │ SPONGE CONSTRUCTION │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ Absorption Phase: │ │ M₁ ──► XOR ──► P ──► XOR ──► P ──► ... │ │ State State │ │ │ │ Squeezing Phase: │ │ State ──► P ──► Extract ──► h₁ ──► P ──► Extract ──► h₂ │ │ │ │ • P is a permutation function (Keccak-p) │ │ • Variable output length │ │ • Resistant to length extension attacks │ └─────────────────────────────────────────────────────────────────┘

Figure 3: Sponge construction (used in SHA-3).

The SHA Family

The Secure Hash Algorithm (SHA) family is a set of cryptographic hash functions published by NIST. The family includes SHA-1, SHA-2, and SHA-3.

SHA Overview

AlgorithmOutput Size (bits)Internal State (bits)Block Size (bits)ConstructionStatus
SHA-1160160512Merkle-DamgårdBroken (deprecated)
SHA-224224256512Merkle-DamgårdSecure
SHA-256256256512Merkle-DamgårdSecure
SHA-3843845121024Merkle-DamgårdSecure
SHA-5125125121024Merkle-DamgårdSecure
SHA-3224/256/384/5121600N/A (sponge)SpongeSecure

SHA-1 and Its Vulnerabilities

SHA-1 (Secure Hash Algorithm 1) was designed by the NSA and published by NIST in 1995 as FIPS 180-1. It produces a 160-bit hash value.

Structure

SHA-1 is a Merkle-Damgård hash with:

Vulnerabilities

SHA-1 has been broken in practice:

⚠️ SHA-1 is insecure
SHA-1 should not be used for any new applications. For existing systems, it should be migrated to SHA-2 or SHA-3. Major browsers and certificate authorities have stopped accepting SHA-1 certificates.

SHA-2 (SHA-224, SHA-256, SHA-384, SHA-512)

SHA-2 was published by NIST in 2001 (FIPS 180-2) to replace SHA-1. It is a family of hash functions with different output sizes, based on the same design principles but with stronger security.

SHA-256

SHA-256 produces a 256-bit hash value. It uses:

Security: SHA-256 provides 128 bits of collision resistance (birthday bound) and 256 bits of preimage resistance. No practical attacks exist.

SHA-512

SHA-512 produces a 512-bit hash value. It uses:

Security: SHA-512 provides 256 bits of collision resistance and 512 bits of preimage resistance.

SHA-224, SHA-384

These are truncated versions of SHA-256 and SHA-512, respectively. They provide output sizes that match the key sizes of certain ciphers (e.g., SHA-224 with 3DES).

Current Status

SHA-2 is considered secure and is the current standard for most applications. The U.S. government mandates SHA-2 for cryptographic applications (FIPS 180-4).

Recommendation: Use SHA-256 or SHA-512 for most applications. For extremely high-security environments (e.g., classified information), SHA-512 is preferred.

SHA-3 (Keccak)

SHA-3 was selected by NIST in 2015 (FIPS 202) after a public competition. The winning algorithm was Keccak, designed by Guido Bertoni, Joan Daemen, Michaël Peeters, and Gilles Van Assche.

SHA-3 uses the sponge construction with the Keccak-p permutation, which operates on a 1600-bit state. It supports output sizes of 224, 256, 384, and 512 bits.

Why SHA-3?

SHA-3 Variants

VariantOutput Size (bits)Security Level (bits)
SHA3-224224112 (collision), 224 (preimage)
SHA3-256256128 (collision), 256 (preimage)
SHA3-384384192 (collision), 384 (preimage)
SHA3-512512256 (collision), 512 (preimage)

SHAKE (Extendable-Output Functions)

SHA-3 also includes SHAKE128 and SHAKE256, which are extendable-output functions (XOFs). They produce variable-length output, similar to a random oracle.

Use: SHAKE is useful when a variable-length output is needed, such as in key derivation.

Other Hash Algorithms

MD5 (Message Digest Algorithm 5)

MD5 produces a 128-bit hash value. It was designed by Ron Rivest in 1991.

BLAKE2

BLAKE2 is a cryptographic hash function designed by Jean-Philippe Aumasson, Samuel Neves, Zooko Wilcox-O'Hearn, and Christian Winnerlein. It is faster than SHA-2 and SHA-3 and provides security comparable to SHA-3.

Comparison

AlgorithmOutput SizeSpeed (Software)Security Status
MD5128 bitsFastBroken
SHA-1160 bitsFastBroken
SHA-256256 bitsModerateSecure
SHA-512512 bitsModerateSecure
SHA3-256256 bitsSlower (software)Secure
BLAKE2b512 bitsVery fastSecure

Applications of Hash Functions

1. Password Storage

Instead of storing passwords in plaintext, systems store a hash of the password. When a user enters a password, it is hashed and compared to the stored hash.

Key Concepts:

Password Storage Example
salt = random(16 bytes)
hash = SHA256(salt + password)
store(salt, hash)
Verification: SHA256(retrieved_salt + input_password) == stored_hash

2. Data Integrity Verification

Hash functions are used to verify that a file or message has not been altered.

3. Digital Signatures

In digital signatures, the message is hashed and the hash is signed, rather than signing the entire message. This is more efficient because the hash is much smaller than the message.

┌─────────────────────────────────────────────────────────────────┐ │ DIGITAL SIGNATURE WITH HASHING │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ Signing: │ │ Message ──► Hash ──► Sign with Private Key ──► Signature │ │ │ │ Verification: │ │ Message ──► Hash ──► Verify Signature with Public Key │ │ │ │ • Only the hash is signed, not the entire message │ │ • The hash provides integrity protection │ │ • The signature provides authentication and non-repudiation │ └─────────────────────────────────────────────────────────────────┘

Figure 4: Digital signature with hashing.

4. Message Authentication Codes (MACs)

HMAC (Hash-based Message Authentication Code) uses a hash function with a secret key to provide message authentication. We will cover MACs in detail in Tutorial 2.10.

5. Blockchain and Merkle Trees

Hash functions are fundamental to blockchain technology:

┌─────────────────────────────────────────────────────────────────┐ │ MERKLE TREE │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ Root Hash │ │ / \ │ │ / \ │ │ Hash12 Hash34 │ │ / \ / \ │ │ / \ / \ │ │ Hash1 Hash2 Hash3 Hash4 │ │ | | | | │ │ Tx1 Tx2 Tx3 Tx4 │ │ │ │ • Efficient verification of transactions │ │ • Used in Bitcoin, Ethereum, and many other blockchains │ │ • Hash is typically SHA-256 (or other secure hash) │ └─────────────────────────────────────────────────────────────────┘

Figure 5: Merkle tree structure.

6. Hash-Based Data Structures

Security Analysis of Hash Functions

Birthday Attack and Collision Resistance

The birthday paradox states that for an n-bit hash, the expected number of hashes needed to find a collision is approximately 2n/2. For SHA-256 (n=256), this is 2128 operations, which is infeasible.

This is why hash functions need to be at least 256 bits to provide 128 bits of collision security.

Length Extension Attack

In Merkle-Damgård hash functions (MD5, SHA-1, SHA-2), given H(M) and the length of M, it is possible to compute H(M || padding || X) without knowing M. This is the length extension attack.

Mitigation: Use HMAC (which hashes the key before and after the message) or use a hash function with a different construction (SHA-3 is immune to length extension attacks).

Side-Channel Attacks

Hash functions can be vulnerable to side-channel attacks (timing, power consumption) if not implemented with constant-time code. Most hash functions are designed to run in constant time, but implementation bugs can introduce vulnerabilities.

Post-Quantum Security

Quantum computers using Grover's algorithm can find a preimage in 2n/2 operations (instead of 2n). This means that SHA-256 provides 128 bits of preimage resistance against quantum attacks, while SHA-512 provides 256 bits.

Status of Hash Functions

AlgorithmCollision ResistancePreimage ResistanceStatus
MD5Broken (216)Weak (2122)Deprecated
SHA-1Broken (263)2160 (theoretical)Deprecated
SHA-2562128 (secure)2256 (secure)Recommended
SHA-5122256 (secure)2512 (secure)Recommended
SHA3-2562128 (secure)2256 (secure)Recommended

Standards and Recommendations

Recommendations

Case Studies

Case Study 1: The MD5 Collision Attack (2004-2012)

In 2004, researchers demonstrated practical collisions for MD5. In 2012, the Flame malware used an MD5 collision to forge a Microsoft certificate, allowing it to masquerade as a legitimate Windows Update. This demonstrated that MD5 was not only theoretically broken but practically exploitable.

Lesson: Hash functions with known weaknesses must be replaced immediately. Relying on them for security-critical applications is dangerous.

Case Study 2: The SHA-1 Collision (SHAttered, 2017)

In 2017, Google and CWI Amsterdam announced the first practical SHA-1 collision. They produced two different PDF files with the same SHA-1 hash. The attack required about 263.1 operations (110 GPU years, costing about $110,000).

Impact: Major browsers stopped accepting SHA-1 certificates. Certificate authorities stopped issuing SHA-1 certificates. NIST officially deprecated SHA-1.

Lesson: Even with a large security margin (280), advances in cryptanalysis and computing power can break algorithms sooner than expected.

Case Study 3: LinkedIn Password Breach (2012)

In 2012, LinkedIn suffered a data breach where 6.5 million passwords were stolen. The passwords were stored using SHA-1 hashes without salts. Attackers were able to crack many of the passwords using rainbow tables and brute-force attacks.

Lesson: Hashing passwords without salts is insecure. Use salted hashes with key stretching functions (bcrypt, scrypt, Argon2).

Key Takeaways

Section Summaries

Quiz

  1. What are the three core properties of a cryptographic hash function?
  2. AnswerPreimage resistance (one-way), second preimage resistance, and collision resistance.
  3. What is the birthday attack, and how does it affect collision resistance?
  4. AnswerThe birthday attack uses the birthday paradox to find collisions. For an n-bit hash, the expected number of hashes needed to find a collision is about 2n/2. This means that collision resistance is only half the bit length of the hash.
  5. Why is SHA-1 considered insecure?
  6. AnswerSHA-1 is considered insecure because practical collision attacks have been demonstrated (e.g., SHAttered in 2017). The security margin is no longer sufficient against modern computing power and cryptanalytic techniques.
  7. What is the difference between SHA-2 and SHA-3?
  8. AnswerSHA-2 uses the Merkle-Damgård construction and is vulnerable to length extension attacks (when used without HMAC). SHA-3 uses the sponge construction and is immune to length extension attacks. They are based on different design principles.
  9. What is a salt in password hashing, and why is it important?
  10. AnswerA salt is a random value added to a password before hashing. It ensures that identical passwords produce different hashes, preventing rainbow table attacks. Each password gets a unique salt.
  11. What is the length extension attack, and which hash functions are vulnerable to it?
  12. AnswerThe length extension attack allows an attacker to compute H(M || padding || X) from H(M) without knowing M. Hash functions using the Merkle-Damgård construction (MD5, SHA-1, SHA-2) are vulnerable. SHA-3 (sponge construction) is immune.
  13. What is the recommended hash function for digital signatures today?
  14. AnswerSHA-256, SHA-512, or SHA-3 (SHA3-256, SHA3-512). SHA-1 and MD5 are deprecated.
  15. What is a Merkle tree, and how is it used in blockchain?
  16. AnswerA Merkle tree is a binary tree where each leaf is a hash of a transaction and each internal node is the hash of its children. It is used in blockchain to efficiently verify transactions without downloading the entire blockchain.
  17. What is the avalanche effect in the context of hash functions?
  18. AnswerThe avalanche effect is the property that a small change in input (e.g., flipping one bit) results in a significant change in output (approximately half the output bits change). It ensures that similar inputs produce very different hashes.
  19. How does SHA-3 differ from SHA-2 in terms of construction and security?
  20. AnswerSHA-3 uses the sponge construction with the Keccak-p permutation, while SHA-2 uses the Merkle-Damgård construction. SHA-3 is immune to length extension attacks and has different performance characteristics (often slower in software but faster in hardware). Both provide similar security levels for the same output size.

Exercises

  1. Hash Computation (Conceptual)

    Using the SHA-256 algorithm conceptually, explain what happens when you hash the string "Hello, World!". What output size is produced, and why is it a fixed size?

  2. Sample Solution

    SHA-256 processes the input by padding it to a multiple of 512 bits, then iteratively applies a compression function to 512-bit blocks, updating an internal 256-bit state. The final state is the 256-bit hash output. The output is fixed at 256 bits regardless of the input size.

  3. Birthday Paradox Calculation

    For a hash function with a 160-bit output (like SHA-1), how many hashes need to be computed to find a collision with 50% probability? How about for a 256-bit hash (like SHA-256)?

  4. Sample Solution

    For an n-bit hash, the birthday bound is approximately 2n/2 hashes.

    For SHA-1 (n=160): 280 ≈ 1.2×1024 hashes.

    For SHA-256 (n=256): 2128 ≈ 3.4×1038 hashes.

    This shows that SHA-256 provides vastly stronger collision resistance than SHA-1.

  5. Password Hashing

    Explain why simply hashing a password with SHA-256 is insufficient for password storage. What additional mechanisms should be used?

  6. Sample Solution

    Simply hashing a password with SHA-256 is insufficient because:

    1. Rainbow tables: Attackers can precompute hashes of common passwords.
    2. Speed: SHA-256 is fast, making brute-force attacks efficient.

    Additional mechanisms:

  7. Length Extension Attack

    Explain how a length extension attack works on SHA-256 and how HMAC mitigates it.

  8. Sample Solution

    In SHA-256 (Merkle-Damgård construction), the state after processing message M can be used to continue hashing with additional data, without knowing M. Given H(M) and the length of M, an attacker can compute H(M || padding || X).

    HMAC mitigates this by hashing the key in two passes: HMAC(K, M) = H(K ⊕ opad || H(K ⊕ ipad || M)). The outer hash prevents the length extension attack because the attacker does not know the inner hash state (it depends on the key).

  9. Merkle Tree Verification

    In a Merkle tree with 8 transactions (Tx1 to Tx8), how many hashes are needed to verify that Tx5 is in the tree? Explain the process.

  10. Sample Solution

    To verify Tx5, you need:

    Path for Tx5: Tx5 → Hash56 → Hash5678 → Root

    You need H(Tx6) (sibling of Tx5), Hash78 (sibling of Hash56), and Hash1234 (sibling of Hash5678) to compute the root. That's 3 hashes plus the root to verify. So 3 hashes are needed (log₂(8) = 3).

Homework

  1. Research: The SHA-3 Competition

    Research the NIST SHA-3 competition (2007-2015). Write a 500-word report that covers:

  2. Sample Answer

    Complete answer would describe that the competition was motivated by the need for a new design in case SHA-2 was broken, and to provide diversity. Finalists included Keccak, BLAKE, Grøstl, JH, and Skein. Keccak was chosen for its security margin, performance in hardware, and simplicity. Advantages of SHA-3 include immunity to length extension attacks, and support for extendable-output functions (SHAKE).

  3. Password Hashing Comparison

    Compare PBKDF2, bcrypt, scrypt, and Argon2. Create a table showing:

    Write a summary recommending which to use and why.

  4. Sample Answer

    Complete answer would include a table with the four algorithms. PBKDF2 is hash-based, not memory-hard, susceptible to GPU attacks; bcrypt is better but still memory-limited; scrypt is memory-hard; Argon2 is the most advanced and memory-hard. Recommendation: Argon2id for new systems (winner of the Password Hashing Competition), otherwise bcrypt or PBKDF2 with high iteration counts.

  5. Analyze a Real-World Hash Function Usage

    Research how Bitcoin uses SHA-256. Write a 500-word report that explains:

  6. Sample Answer

    Complete answer would explain that SHA-256 is used in block hashing (proof-of-work), Merkle trees (transaction verification), and address generation (RIPEMD-160 after SHA-256). Double SHA-256 is used to protect against length extension attacks (though SHA-256 is vulnerable, double hashing mitigates). SHA-256 was chosen for its security and widespread adoption. The security of Bitcoin relies on the collision and preimage resistance of SHA-256.

  7. Length Extension Attack Demonstration

    Research how a length extension attack could be used against a simple authentication scheme that uses H(K || M) where K is a secret key. Describe the attack and how to prevent it.

  8. Sample Answer

    Complete answer would explain that an attacker who knows H(K || M) and the length of M can compute H(K || M || padding || X) without knowing K. This allows the attacker to forge messages with the same authentication tag. Prevention: use HMAC (which hashes the key both before and after the message) or use a hash function immune to length extension attacks (SHA-3).

  9. Mini-Project: Implement a Hash-Based Integrity Checker

    Write a program in your preferred language that:

    Test it with files of different sizes. Write a report on your implementation and any performance observations.

  10. Sample Answer

    Complete answer would include source code, test results (showing that the program detects any modification to the file), and a discussion of performance (e.g., SHA-256 processing speed, the effect of file size on computation time). Observations might include that hashing large files (e.g., > 1 GB) takes a few seconds and is I/O-bound.

Summary

This tutorial has provided a comprehensive examination of cryptographic hash functions and their role in data integrity. We began by defining hash functions and their essential properties: preimage resistance, second preimage resistance, and collision resistance. We explored the design principles behind hash functions, including the Merkle-Damgård construction (used in MD5, SHA-1, SHA-2) and the sponge construction (used in SHA-3).

We surveyed the SHA family in detail, from SHA-1 (now broken) to SHA-2 (secure and recommended) to SHA-3 (a modern alternative with a different design). We also discussed other algorithms such as MD5 (broken) and BLAKE2 (secure and fast).

We examined real-world applications of hash functions, including password storage (with salts and key stretching), data integrity verification, digital signatures, message authentication codes, and blockchain (Merkle trees). Each application demonstrates the versatility and importance of hash functions in modern security.

We analyzed security considerations, including the birthday attack (which reduces collision resistance to 2n/2), length extension attacks (affecting Merkle-Damgård constructions), and side-channel attacks. We discussed the importance of using appropriate hash functions for different contexts and the standards that guide their use.

The case studies illustrated the practical consequences of hash function weaknesses: the MD5 collision attack used in Flame malware, the SHA-1 collision demonstrated in SHAttered, and the LinkedIn password breach. These incidents underscore the importance of using secure hash functions and following best practices for password storage.

With this foundation, you are now equipped to select and use hash functions appropriately in cryptographic systems, understand their security properties, and recognize the risks associated with weaker algorithms.

Connection to the Next Tutorial

In Tutorial 2.10: Message Authentication Codes (MACs), we will build on hash functions to provide message authentication. HMAC (Hash-based Message Authentication Code) uses hash functions to provide both integrity and authentication, addressing the limitations of hash functions alone.