intermediatecat/crypto~2 min read

Hash Attacks & Length Extension

Exploit Merkle–Damgård hash functions (MD5, SHA-1, SHA-256) with length extension attacks and hash collision techniques.

1. Length Extension Attacks

Length extension attacks exploit cryptographic hash functions built on the Merkle–Damgård construction (such as MD5, SHA-1, SHA-256).

The Flaw

Given a hash $H(\text{secret} \parallel \text{data})$ and the length of the secret, an attacker can compute $H(\text{secret} \parallel \text{data} \parallel \text{padding} \parallel \text{custom_append})$ without knowing the secret!

This occurs because Merkle–Damgård hashes process data in blocks, and the hash output is simply the internal state of the compression function after processing the final block.

+------------------+----------------+---------------------+
| Secret + Message |  Hash Padding  | Attacker Data Extension |
+------------------+----------------+---------------------+
| <----- Original Hash H1 -----> |
                                  | ---> New Hash H2 computed offline

Vulnerable Application Pattern

API authentication using simple MAC signature:

signature = MD5( secret_key + "user=guest&role=user" )

Attacker wants to append &role=admin.

Automated Attack with hashpump

# Command: hashpump -s <signature> -d <data> -a <append> -k <key_length>
hashpump -s 6032333ac1a774eb066d77366838a39c \
         -d "user=guest&role=user" \
         -a "&role=admin" \
         -k 16

Output gives both the new hash signature and the raw payload containing binary padding bytes:

Signature: 8d8a705a610e7552555541680689b908
Payload: user=guest&role=user\x80\x00\x00\x00...\x00\x00\x01\x20&role=admin

2. Cryptographic Hash Collisions

A hash collision occurs when two distinct inputs $m_1 \neq m_2$ yield the same hash $H(m_1) = H(m_2)$.

MD5 Collisions (Fastcoll / Uncoll)

MD5 is completely broken against collision attacks. Tools like fastcoll generate two different prefix-chosen binary payloads that output identical MD5 hashes in seconds.

# Generate two colliding files with identical prefix
fastcoll -p prefix.bin -o file1.bin file2.bin

# Verify MD5 hashes match
md5sum file1.bin file2.bin

SHA-1 Collisions (SHAttered)

In 2017, CISO/Google published SHAttered, producing two PDF documents with identical SHA-1 hashes but different visible content.


Secure Countermeasures (HMAC)

To prevent length extension attacks, applications must use HMAC (Hash-based Message Authentication Code) rather than simple concatenation:

$$\text{HMAC}(K, M) = H\big((K \oplus \text{opad}) \parallel H((K \oplus \text{ipad}) \parallel M)\big)$$

Or adopt modern sponge-construction hashes like SHA-3 or BLAKE2/BLAKE3, which are inherently immune to length extension attacks.