MD5, SHA-1 and SHA-256 in C++: Tested Hash Functions, Collisions and Length Extension

MD5, SHA-1 and SHA-256 tested in five languages, with a real MD5 collision, a length-extension attack and when to switch to OpenSSL.

Two 128-byte inputs shown as grids of cells that differ in six red cells, both feeding one identical MD5 digest.

Two different 128-byte inputs, differing in just six bytes, produce the same MD5 digest: 79054025255fb1a26e4bc422aef54eb4. The same two inputs produce different SHA-256 digests. Both facts are printed by the programs on this page, and together they explain why MD5 left security work years ago while SHA-256 stayed.

This guide builds MD5, SHA-1 and SHA-256 from scratch in C and C++, shows the same digests from the standard libraries of Java, Python and C#, and then breaks them on purpose: a real collision, a length-extension forgery and three bugs that silently produce wrong hashes. Every program was compiled and run for this article on Ubuntu 24.04 with GCC 13.3 and Clang 18 (-std=c11, -std=c17, -std=c++17, -std=c++20, warnings enabled), OpenJDK 21, Python 3.13 and the .NET 8 SDK, and all five languages print the same digests. The tests check them against RFC and FIPS vectors, and the C code also runs clean under AddressSanitizer and UndefinedBehaviorSanitizer.

The Short Answer

Which hash should I use? SHA-256 for fingerprints and integrity checks, HMAC-SHA-256 to authenticate a message with a secret, and Argon2id for passwords. MD5 and SHA-1 only belong in code that must match an existing format and does not defend against an attacker.

Is MD5 broken? For collision resistance, yes: anyone can produce two inputs with the same MD5 (the program in the collisions section does it with 128 bytes). For catching accidental corruption it still works.

Should I write my own? Write one to learn how hashing works, and use OpenSSL or your platform’s library for anything real. The testing section shows how to prove your own version correct, and the performance table shows what it costs.

What Is a Message Digest?

A message digest is a fixed-size fingerprint that a hash function computes from data of any length. The same input always gives the same digest, a tiny change to the input changes the digest completely, and a secure hash function makes it infeasible to recover the input or to find two inputs that share a digest.

A digest is not encryption and not encoding. Base64 is reversible by design; a digest throws information away, so there is nothing to decode. RFC 1321 defines MD5 and the FIPS 180-4 standard defines SHA-1 and SHA-256.

AspectMD5SHA-1SHA-256
Digest size128 bits (16 bytes)160 bits (20 bytes)256 bits (32 bytes)
Block size64 bytes64 bytes64 bytes
Steps per block648064
Published1992 (RFC 1321)19952002 (FIPS 180-2)
CollisionsPractical since 2004Practical since 2017None known
Length extensionVulnerableVulnerableVulnerable
StatusNon-security checksums onlyNIST retires it by 31 December 2030Current

All three share one design, the Merkle–Damgård construction, and that shared design is why one function in the code below serves all three.

How the Three Hashes Work

Each hash cuts the message into 64-byte blocks and runs every block through a compression function that updates a small internal state. The digest is the final state. The last block needs padding so the message fills whole blocks, and the padding also records the message length.

The padding rule is the same for all three: append one 0x80 byte, then zeros until the length is 56 modulo 64, then the message length in bits as a 64-bit number. MD5 writes that number little-endian; SHA-1 and SHA-256 write it big-endian. Fifty-five bytes fit in one block with their padding. Fifty-six bytes need two, and that boundary is where most hand-written implementations fail.

The C implementation puts everything the three share in one place. This excerpt from digest.c buffers input into blocks, builds the padding and finishes the hash:

/* ---- The part all three share: buffer into 64-byte blocks, pad, finish. ---- */

typedef void (*block_fn)(uint32_t h[8], const uint8_t block[64]);

static void md_update(digest_ctx *c, block_fn compress, const void *data, size_t len)
{
    const uint8_t *p = data;
    size_t used = (size_t)(c->bytes & 63);
    c->bytes += len;
    if (used != 0) {                       /* top up a partly filled block first */
        size_t take = 64 - used;
        if (take > len)
            take = len;
        memcpy(c->buf + used, p, take);
        p += take;
        len -= take;
        if (used + take < 64)
            return;
        compress(c->h, c->buf);
    }
    for (; len >= 64; p += 64, len -= 64)  /* whole blocks straight from the input */
        compress(c->h, p);
    memcpy(c->buf, p, len);                /* keep the tail for next time */
}

size_t digest_padding(uint64_t msg_len, int big_endian_length, uint8_t out[72])
{
    size_t zeros = (size_t)((55 - (msg_len & 63)) & 63);   /* so that length + 1 + zeros = 56 mod 64 */
    size_t n = 1 + zeros;
    uint64_t bits = msg_len * 8;
    out[0] = 0x80;
    memset(out + 1, 0, zeros);
    for (int i = 0; i < 8; ++i)
        out[n + (size_t)i] = (uint8_t)(bits >> (big_endian_length ? 56 - 8 * i : 8 * i));
    return n + 8;
}

static void md_final(digest_ctx *c, block_fn compress, int big_endian, size_t words,
                     uint8_t *out)
{
    uint8_t pad[72];
    uint64_t msg_len = c->bytes;
    size_t n = digest_padding(msg_len, big_endian, pad);
    md_update(c, compress, pad, n);        /* the padding completes the last block */
    for (size_t i = 0; i < words; ++i) {
        if (big_endian)
            store_be32(out + 4 * i, c->h[i]);
        else
            store_le32(out + 4 * i, c->h[i]);
    }
    memset(c, 0, sizeof *c);
}

Each hash then supplies only its own compression function. MD5 runs 64 steps over four round functions, SHA-1 runs 80 steps over a message schedule, and SHA-256 runs 64 steps with the Ch, Maj and sigma functions. The MD5 sine constants and the SHA-256 round constants were computed by gen/tables.py in the C repository (from sines and prime roots) and pasted into digest.c rather than typed from a book, and a mutation test that changes one constant confirms the tests notice.

Hashing in Each Language

The five programs below hash the same three messages. C and C++ use the code in this repository. Java, Python and C# call their standard libraries, which is what you should do in real projects. All five print identical output.

C

/* digest_demo.c - MD5, SHA-1 and SHA-256 of three short messages.
 * Build: gcc -std=c11 -Wall -Wextra -pedantic digest_demo.c digest.c -o digest_demo
 */
#include <stdio.h>
#include <string.h>

#include "digest.h"

static void show(const char *label, const char *text)
{
    uint8_t d[SHA256_DIGEST_SIZE];
    char h[2 * SHA256_DIGEST_SIZE + 1];
    size_t n = strlen(text);

    printf("message: \"%s\" (%zu bytes)\n", label, n);
    md5(text, n, d);
    digest_to_hex(d, MD5_DIGEST_SIZE, h);
    printf("  MD5     %s\n", h);
    sha1(text, n, d);
    digest_to_hex(d, SHA1_DIGEST_SIZE, h);
    printf("  SHA-1   %s\n", h);
    sha256(text, n, d);
    digest_to_hex(d, SHA256_DIGEST_SIZE, h);
    printf("  SHA-256 %s\n", h);
}

int main(void)
{
    show("", "");
    show("abc", "abc");
    show("The quick brown fox jumps over the lazy dog", "The quick brown fox jumps over the lazy dog");
    return 0;
}

C++

The C++17 version wraps the three hashes in one class template, so hash<Sha256>(text) and hash<Md5>(text) share a single code path.

// digest_demo.cpp - MD5, SHA-1 and SHA-256 of three short messages.
// Build: g++ -std=c++17 -Wall -Wextra -Iinclude src/digest_demo.cpp -o digest_demo
#include <cstdio>
#include <string_view>

#include "digest.hpp"

static void show(std::string_view text)
{
    std::printf("message: \"%.*s\" (%zu bytes)\n", static_cast<int>(text.size()), text.data(), text.size());
    std::printf("  MD5     %s\n", mycplus::to_hex(mycplus::hash<mycplus::Md5>(text)).c_str());
    std::printf("  SHA-1   %s\n", mycplus::to_hex(mycplus::hash<mycplus::Sha1>(text)).c_str());
    std::printf("  SHA-256 %s\n", mycplus::to_hex(mycplus::hash<mycplus::Sha256>(text)).c_str());
}

int main()
{
    show("");
    show("abc");
    show("The quick brown fox jumps over the lazy dog");
}

Java

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;

/**
 * MD5, SHA-1 and SHA-256 of three short messages, with the digests that java.security
 * provides. Build: javac -d build src/*.java
 */
public final class DigestDemo {
    private DigestDemo() { }

    /** Hex digest of the UTF-8 bytes of text, for an algorithm name such as "SHA-256". */
    static String digestHex(String algorithm, byte[] data) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        return HexFormat.of().formatHex(md.digest(data));
    }

    private static void show(String text) throws NoSuchAlgorithmException {
        byte[] data = text.getBytes(StandardCharsets.UTF_8);
        System.out.print("message: \"" + text + "\" (" + data.length + " bytes)\n");
        System.out.print("  MD5     " + digestHex("MD5", data) + "\n");
        System.out.print("  SHA-1   " + digestHex("SHA-1", data) + "\n");
        System.out.print("  SHA-256 " + digestHex("SHA-256", data) + "\n");
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        show("");
        show("abc");
        show("The quick brown fox jumps over the lazy dog");
    }
}

Python

"""MD5, SHA-1 and SHA-256 of three short messages, with hashlib.

Run: python digest_demo.py
"""
import hashlib
import hmac


def digest_hex(algorithm: str, data: bytes) -> str:
    """Hex digest of data for a hashlib algorithm name such as "sha256"."""
    return hashlib.new(algorithm, data).hexdigest()


def tags_match(expected: str, received: str) -> bool:
    """Compare two hex digests in constant time, as a real verifier must."""
    return hmac.compare_digest(expected, received)


def show(text: str) -> None:
    data = text.encode("utf-8")
    print(f'message: "{text}" ({len(data)} bytes)')
    print(f"  MD5     {digest_hex('md5', data)}")
    print(f"  SHA-1   {digest_hex('sha1', data)}")
    print(f"  SHA-256 {digest_hex('sha256', data)}")


def main() -> None:
    show("")
    show("abc")
    show("The quick brown fox jumps over the lazy dog")


if __name__ == "__main__":
    main()

C#

The .NET analyzers flag MD5 and SHA-1 as broken algorithms (rules CA5351 and CA5350) and the repository builds with analyzers as errors. The code suppresses each warning at the call with a reason, which is also good practice in your own code: the suppression documents that the weak hash is deliberate.

using System;
using System.Security.Cryptography;
using System.Text;

namespace MyCPlus.Cryptography;

/// <summary>MD5, SHA-1 and SHA-256 of three short messages, with System.Security.Cryptography.</summary>
public static class Program
{
    // The analyzers flag MD5 and SHA-1 (CA5351, CA5350). They are used here because the page is
    // about them, and each call says so with a suppression and a reason.
    private static string Md5Hex(byte[] data) =>
#pragma warning disable CA5351 // Do not use broken cryptographic algorithms: shown on purpose
        Convert.ToHexString(MD5.HashData(data)).ToLowerInvariant();
#pragma warning restore CA5351

    private static string Sha1Hex(byte[] data) =>
#pragma warning disable CA5350 // Do not use weak cryptographic algorithms: shown on purpose
        Convert.ToHexString(SHA1.HashData(data)).ToLowerInvariant();
#pragma warning restore CA5350

    private static string Sha256Hex(byte[] data) =>
        Convert.ToHexString(SHA256.HashData(data)).ToLowerInvariant();

    private static void Show(string text)
    {
        byte[] data = Encoding.UTF8.GetBytes(text);
        Console.Out.Write($"message: \"{text}\" ({data.Length} bytes)\n");
        Console.Out.Write($"  MD5     {Md5Hex(data)}\n");
        Console.Out.Write($"  SHA-1   {Sha1Hex(data)}\n");
        Console.Out.Write($"  SHA-256 {Sha256Hex(data)}\n");
    }

    public static void Main()
    {
        Show("");
        Show("abc");
        Show("The quick brown fox jumps over the lazy dog");
    }
}

Output (identical in all five languages):

message: "" (0 bytes)
  MD5     d41d8cd98f00b204e9800998ecf8427e
  SHA-1   da39a3ee5e6b4b0d3255bfef95601890afd80709
  SHA-256 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
message: "abc" (3 bytes)
  MD5     900150983cd24fb0d6963f7d28e17f72
  SHA-1   a9993e364706816aba3e25717850c26c9cd0d89d
  SHA-256 ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
message: "The quick brown fox jumps over the lazy dog" (43 bytes)
  MD5     9e107d9d372bb6826bd81d3542a419d6
  SHA-1   2fd4e1c67a2d28fced849ee1bb76e7391b93eb12
  SHA-256 d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592

The empty-message row for each algorithm and the abc row come straight from RFC 1321 and FIPS 180-4. The third message is the classic pangram used in countless documents.

How to Test a Hash Function

A hash with one wrong constant fails on almost every input, which makes hashing code easy to test and easy to trust too early. The test suite in each repository layers four checks:

  1. Published known answers. Sixteen digests from RFC 1321 and FIPS 180-4, including the million-a message.
  2. Independent vectors. 306 message lengths, from 0 to 305 bytes, hashed by Python’s hashlib and stored in tests/vectors/lengths.txt. The byte at position i is (i*31+7) & 0xFF, so the files are reproducible. The C and C++ tests also hash every message in 7-byte chunks and split it at every offset up to 130 bytes, which exercises the buffering code.
  3. HMAC vectors. Ten cases from RFC 4231 and RFC 2202.
  4. A cross-check against OpenSSL. On Linux, the C test compares 5,000 random messages and keys against OpenSSL’s output for all three hashes and HMAC, 20,000 comparisons in total.

The vector files are identical in all five repositories, and gen/make_vectors.py in the C repository asserts every published digest against hashlib before it writes them.

Do the tests catch real bugs?

A passing suite proves little until you break the code and watch it fail. The C test suite was run against 27 deliberate mutants of digest.c: a changed round constant, a shifted rotation, a padding length off by one, a dropped tail in the buffering code, a swapped HMAC pad byte. The C++ suite does the same with 19 mutants. Every mutant was caught.

The more interesting result is which test caught what. Run on their own, the 16 known answers catch 21 of the 27 mutants, including every compression-function and padding mutant. The six they miss are all in code the known answers never reach: the three HMAC mutants and the three length-extension resume mutants. Adding the HMAC vectors and a resume check brings the count to 27 of 27, and the 306-length sweep and every-offset splits did not catch a single mutant that those did not already catch.

That is a negative result worth stating. The long sweep still earns its place, because boundary bugs are what hand-written hashes typically have and the sweep covers every length around the 55, 56, 64 and 65-byte boundaries. But the mutation run shows that the cheapest protection is the published vectors, plus a test for every feature beyond plain hashing.

Three Mistakes That Break Hashing Code

Each of these produces a plausible-looking digest, which is why they survive into production. Each has a short program in the pitfalls/ directory with captured output.

Printing through a signed char

On x86 and MSVC, plain char is signed. Print a byte above 0x7F through it with %02x and the value sign-extends:

/* hex_sign_extension.c - printing a digest through a signed char buffer.
 * On x86, plain `char` is signed, and printf("%02x") of a negative char prints ffffff90.
 */
#include <stdio.h>

#include "digest.h"

int main(void)
{
    uint8_t digest[MD5_DIGEST_SIZE];
    md5("abc", 3, digest);

    signed char wrong[MD5_DIGEST_SIZE];       /* what a plain char buffer is on x86 and MSVC */
    for (size_t i = 0; i < sizeof digest; ++i)
        wrong[i] = (signed char)digest[i];

    printf("printed through signed char:\n  ");
    for (size_t i = 0; i < 4; ++i)
        printf("%02x ", wrong[i]);
    printf("...\nprinted through uint8_t:\n  ");
    for (size_t i = 0; i < 4; ++i)
        printf("%02x ", digest[i]);
    printf("...\n");
    return 0;
}

Output:

printed through signed char:
  ffffff90 01 50 ffffff98 ...
printed through uint8_t:
  90 01 50 98 ...

Digest buffers should be uint8_t or unsigned char, always.

Calling strlen() on binary data

A zero byte ends a C string, so strlen() stops at the first one. Here a three-byte record hashes as one byte:

/* strlen_on_binary.c - hashing binary data with strlen(). A zero byte ends the "length". */
#include <stdio.h>
#include <string.h>

#include "digest.h"

static void show(const char *label, const uint8_t *data, size_t len)
{
    uint8_t d[SHA256_DIGEST_SIZE];
    char h[2 * SHA256_DIGEST_SIZE + 1];
    sha256(data, len, d);
    digest_to_hex(d, SHA256_DIGEST_SIZE, h);
    printf("%-24s %2zu bytes  %s\n", label, len, h);
}

int main(void)
{
    const uint8_t record[] = { 'a', 0x00, 'b' };   /* three bytes, one of them zero */
    show("hashed with strlen():", record, strlen((const char *)record));
    show("hashed with sizeof:", record, sizeof record);
    return 0;
}

Output:

hashed with strlen():     1 bytes  ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb
hashed with sizeof:       3 bytes  59b271ae1bbcb1d31d41929817f4b16fb439eb4f31520b5ad1d5ce98920a7138

Pass the length explicitly whenever the data is not text.

Hashing the newline

fgets() keeps the trailing newline, and "abc\n" is a different message from "abc". The pitfall program in the repository hashes both and the stripped line:

"abc":             ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
"abc\n" (fgets):   edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb
after stripping:   ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

This is the most common reason a hash computed in code disagrees with the one from sha256sum or an online tool. When two digests differ and you cannot see why, compare the byte lengths first.

Length Extension: Why H(secret + message) Is Not a Signature

A tempting design for signing a request is tag = SHA-256(secret + message). It fails because the digest of a Merkle–Damgård hash is its final internal state. Anyone who holds the tag and knows the message length can load that state back into a SHA-256 context, append more data and compute the valid tag for the longer message, without ever seeing the secret.

The only unknown is the secret’s length, and the attacker simply tries each plausible length. The program below forges a tag for user=alice&amount=100 extended with &amount=1000000:

Length extension: a valid tag without the secret 1. The server hashes secret + message and publishes the tag secret16 B message21 B padding27 B tag = state after block 1 e7da690a…b2241e83 2. The attacker resumes from that state and appends a suffix block 1: never seen, its output state is the tag suffix15 B padding49 B forged tag: ffd77dbc…719ddbf9 3. The server re-hashes secret + message + padding + suffix secret16 B message21 B padding27 B suffix15 B padding49 B tag: ffd77dbc…719ddbf9 (identical, so the forged message is accepted) HMAC-SHA-256 hashes the key twice, so a published tag is not a resumable state.
Figure 1: The tag is the hash state after block 1. An attacker who knows the message and its tag can restart from that state, append a suffix and compute the tag the server will compute for the longer message.

The attack needs two pieces of code from the repository. sha256_resume() and md5_resume() load a digest back into a context, and the loop below guesses the secret length, resumes from the published tag and checks the result against what the server would compute:

static void attack(const scheme *s, const char *message, const char *suffix)
{
    uint8_t tag[SHA256_DIGEST_SIZE], forged_tag[SHA256_DIGEST_SIZE];
    char hex_tag[2 * SHA256_DIGEST_SIZE + 1];
    size_t msg_len = strlen(message), suffix_len = strlen(suffix);

    sign(s, (const uint8_t *)message, msg_len, tag);
    digest_to_hex(tag, s->size, hex_tag);
    printf("%s: the server signed \"%s\" and published the tag\n  %s\n", s->name, message, hex_tag);

    /* The attacker knows the message, the tag and the algorithm, but not the secret
     * or even its length, so tries every plausible length. */
    for (size_t guess = 1; guess <= 32; ++guess) {
        uint8_t glue[72], forged_msg[256];
        size_t glue_len = digest_padding(guess + msg_len, s->big_endian_length, glue);

        digest_ctx c;
        s->resume(&c, tag, guess + msg_len + glue_len);   /* continue from the published tag */
        s->update(&c, suffix, suffix_len);
        s->final(&c, forged_tag);

        memcpy(forged_msg, message, msg_len);              /* message || padding || suffix */
        memcpy(forged_msg + msg_len, glue, glue_len);
        memcpy(forged_msg + msg_len + glue_len, suffix, suffix_len);
        size_t forged_len = msg_len + glue_len + suffix_len;

        uint8_t expected[SHA256_DIGEST_SIZE];
        sign(s, forged_msg, forged_len, expected);         /* what the server computes */
        if (digest_equal(expected, forged_tag, s->size)) {
            digest_to_hex(forged_tag, s->size, hex_tag);
            printf("  forged message: ");
            print_escaped(forged_msg, forged_len);
            printf("\n  forged tag:     %s\n", hex_tag);
            printf("  the server accepts it (the attacker's guess of the secret length: %zu)\n", guess);
            return;
        }
    }
    printf("  no forgery\n");
}

Output:

SHA-256: the server signed "user=alice&amount=100" and published the tag
  e7da690a0470ca564625a564b244ccb99cf48e787789a58ee5f54b8ab2241e83
  forged message: user=alice&amount=100\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01(&amount=1000000
  forged tag:     ffd77dbc478dba778355e4e7e3dadf417de6498f1a3ead93dacc8c68719ddbf9
  the server accepts it (the attacker's guess of the secret length: 16)

MD5: the server signed "user=alice&amount=100" and published the tag
  f37ee67cd0ed5443f6c132f1072b1a04
  forged message: user=alice&amount=100\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00(\x01\x00\x00\x00\x00\x00\x00&amount=1000000
  forged tag:     ca74f7c43aaed622f1fd96c88312434d
  the server accepts it (the attacker's guess of the secret length: 16)

HMAC-SHA-256: the server signed "user=alice&amount=100" and published the tag
  3420ed03142286a6ee0b807e904003be7ba31f9d73125450e0eae9492b156f1d
  the same attack, guessing every secret length from 1 to 64: rejected every time

The forged message contains the signed text, then the 0x80 marker, zeros and the 64-bit length (\x01( is 296 bits, the length of the secret plus the message), then the attacker’s suffix. The attack works against MD5 as well, with the length written in the other byte order.

HMAC defeats it because it hashes twice with keys derived from the secret, so the published tag is the output of an outer hash, not a state the attacker can continue from. The last block of output shows the same attack failing against HMAC-SHA-256 for every secret length from 1 to 64. RFC 2104 defines HMAC, and RFC 4231 supplies the test vectors the repository checks.

SHA-512/256 and SHA-3 are not vulnerable to length extension, but that is no reason to hand-build a MAC from them. Use HMAC, and compare tags in constant time: CRYPTO_memcmp in OpenSSL, MessageDigest.isEqual in Java, hmac.compare_digest in Python and CryptographicOperations.FixedTimeEquals in C#.

Collisions: Where MD5 and SHA-1 Actually Break

A collision is two different inputs with the same digest. Length extension abuses the design; collisions attack the hash itself, and they are what “broken” means for MD5 and SHA-1.

collisions.c hashes a well-known pair of 128-byte inputs from the 2004 attack by Xiaoyun Wang and colleagues, and a pair of 640-byte SHA-1 collision files from the “SHA-1 is a Shambles” research (Leurent and Peyrin, USENIX Security 2020):

MD5 collision: two 128-byte inputs that differ in 6 bytes
  differing offsets: 19 45 59 83 109 123
  MD5      79054025255fb1a26e4bc422aef54eb4  (input 1)
  MD5      79054025255fb1a26e4bc422aef54eb4  (input 2)
  SHA-256  8d12236e5c4ed9f4e790db4d868fd5c399df267e18ff65c1107c328228cffc98  (input 1)
  SHA-256  b9fef2a8fc93b05e7701e97196fda6c4fbeea25ff8e64fdfee7015eca8fa617d  (input 2)

SHA-1 collision: two 640-byte inputs that differ in 331 bytes
  SHA-1    8ac60ba76f1999a1ab70223f225aefdc78d4ddc0  (input 1)
  SHA-1    8ac60ba76f1999a1ab70223f225aefdc78d4ddc0  (input 2)
  SHA-256  3ead211681cec93d265c8ac123dd062e105408cebf82fa6e2b126f4f40bcb88c  (input 1)
  SHA-256  208feafe1c6a95c73f662514ac48761f25e1f3b74922521a98d9ce287f4a2197  (input 2)

Each pair shares one digest (MD5 for the first, SHA-1 for the second) and has two different SHA-256 digests. SHA-256 has no known collision, and nothing in this output changes that. The MD5 inputs differ in six bytes, at offsets 19, 45, 59, 83, 109 and 123.

The SHA-1 story has three dates. Google and CWI Amsterdam published the first collision in February 2017, the “SHAttered” attack. The 2020 chosen-prefix attack put the cost of a collision with attacker-chosen prefixes at roughly US$45,000. NIST has set 31 December 2030 as the date to stop using SHA-1 in its remaining protocols. For MD5, RFC 6151 updates RFC 1321 with revised security considerations after the collision attacks.

What does that mean for your code?

  • Do not use MD5 or SHA-1 for signatures, certificates, or to decide whether two files are the same when someone hostile may have supplied one of them.
  • You may still use them to detect accidental corruption, or to match an existing format that requires them, as long as no attacker benefits from forging a match.

Don’t Hand-Roll This: Use OpenSSL or Your Platform’s Library

The implementations in this article are for learning and for testing. For real data, call a maintained library. In C++ that usually means OpenSSL’s EVP interface, wrapped in RAII so the context is always freed. This function is the core of openssl_digest.cpp:

// Streaming digest through EVP. Throws if OpenSSL reports an error.
std::string openssl_hex(const EVP_MD* type, std::string_view data)
{
    Ctx ctx(EVP_MD_CTX_new());
    if (!ctx || EVP_DigestInit_ex(ctx.get(), type, nullptr) != 1 ||
        EVP_DigestUpdate(ctx.get(), data.data(), data.size()) != 1)
        throw std::runtime_error("EVP digest failed");
    std::array<unsigned char, EVP_MAX_MD_SIZE> out{};
    unsigned int n = 0;
    if (EVP_DigestFinal_ex(ctx.get(), out.data(), &n) != 1)
        throw std::runtime_error("EVP digest failed");
    static constexpr char hex[] = "0123456789abcdef";
    std::string s;
    for (unsigned int i = 0; i < n; ++i) {
        s += hex[out[i] >> 4];
        s += hex[out[i] & 15];
    }
    return s;
}

The program hashes abc and an HMAC test case through OpenSSL and through the C++ code from this article, then compares them:

MD5          900150983cd24fb0d6963f7d28e17f72  matches digest.hpp
SHA-1        a9993e364706816aba3e25717850c26c9cd0d89d  matches digest.hpp
SHA-256      ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad  matches digest.hpp
HMAC-SHA-256 5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843  matches digest.hpp

The libraries are faster too, and the gap is large.

How This Was Measured

SettingValue
Date21 November 2026
Hardware2-vCPU Intel Xeon @ 2.10 GHz cloud container (SHA and AVX2 instruction flags present)
OS and toolchainUbuntu 24.04, GCC 13.3, CMake Release build, OpenSSL 3.0.13
Workload64 MiB hashed through 64 KiB update calls, one thread
StatisticMedian of 5 runs, reported as MB/s of input
Included in the timingContext initialisation, all updates, finalisation
Checked firstBoth sides produce the same digest of the same buffer

Not captured: percentiles, CPU pinning and frequency-scaling control. This is a shared cloud container, so the absolute numbers will differ on your machine; treat the ratios as the finding. The run was repeated three times and the ranges below cover all three.

HashThis article’s C codeOpenSSL 3.0.13OpenSSL faster by
MD5396–422 MB/s627–638 MB/s1.5–1.6×
SHA-1169–185 MB/s1,303–1,684 MB/s7.7–9.6×
SHA-256195–273 MB/s1,412–1,519 MB/s5.6–7.2×

MD5 shows the smallest gap and SHA-1 and SHA-256 show the largest. The CPU reports the SHA instruction-set extension, which is the likely reason, but this benchmark did not confirm that OpenSSL used it, so treat that as a hypothesis. Whatever the cause, a straightforward C implementation leaves a factor of five to ten on the table for the hashes that matter.

Hashing is also the wrong tool for passwords. A fast hash is exactly what an attacker wants. OWASP’s Password Storage Cheat Sheet recommends Argon2id, with a minimum of 19 MiB of memory, two iterations and one degree of parallelism. Block ciphers such as the Serpent cipher solve a different problem again, and the same rule applies: learn from the implementation, ship the library.

Which Hash Should You Use?

NeedUseWhy
Fingerprint a file or detect tamperingSHA-256No known collisions; available everywhere
Authenticate a message with a shared secretHMAC-SHA-256Immune to length extension; compare in constant time
Store a passwordArgon2id (scrypt or bcrypt if it is unavailable)Deliberately slow and memory-hard
Match a legacy format that requires MD5 or SHA-1The legacy hash, isolated and documentedInteroperability, not security
Catch accidental corruption, no attacker involvedCRC32, MD5 or SHA-256Any works; pick the one your tools already use

Key Takeaways

  • MD5, SHA-1 and SHA-256 share one design. Pad to 64-byte blocks, compress each block, output the final state. One shared padding function serves all three.
  • MD5 and SHA-1 have practical collisions, shown here with real inputs. SHA-256 has none known.
  • SHA-256(secret + message) is not a MAC. Length extension forges a valid tag without the secret; HMAC-SHA-256 stops it.
  • Published vectors catch nearly everything. Sixteen RFC and FIPS answers caught 21 of 27 deliberate bugs; HMAC and resume tests caught the rest.
  • Three quiet bugs produce wrong digests: a signed char, strlen() on binary data and a trailing newline.
  • Use a library for real work, which was 1.5 to 9.6 times faster than the plain C code here. Use Argon2id for passwords.

Frequently Asked Questions

Conclusion

Hash functions look like magic until you write one. The padding rule, the block loop and the final state are about fifty lines of shared code, and once you can see the state you can see why length extension works and why HMAC wraps the hash twice. The collision pair makes the same point from the other side: “broken” means someone built two inputs, and you can print them.

The next step is to run the code. Clone the repository for your language, change one constant in digest.c and watch the tests fail, then explore the other computer science and algorithm articles on MYCPLUS. Revisit this page when NIST’s SHA-1 deadline approaches in 2030 or if a new attack on SHA-256 is published.

Source Code and Tests

C examples
C++ examples
Java examples
Python examples
C# examples

All programs on this page are in the cryptography/hash-functions directory of the MYCPLUS example repositories: C, C++, Java, Python and C#.

Build and test:

cd cryptography/hash-functions
sh run_all.sh

On Windows, run .\run_all.ps1 from PowerShell in the same directory.

What the build checks. Every repository compiles with warnings as errors and runs its vector tests. The demos, the collision demo, the length-extension attack and the three pitfalls must print exactly the files in tests/expected/. The C and C++ repositories also run the mutation script, and the C repository compiles under MSVC /W4 /WX and compares 20,000 digests and MACs with OpenSSL on Linux. CI does not run the benchmark, and it does not test for timing side channels.

What I Verified

CheckUbuntu 24.04Windows 11
C: build and tests, C11 and C17GCC 13.3 and Clang 18, zero warnings, all vectors passMSVC /W4 /WX, C11 and C17, all tests pass
C: AddressSanitizer and UndefinedBehaviorSanitizerCleanNot applicable
C: Valgrind (vector tests and length-extension demo)CleanNot applicable
C: mutation tests27 of 27 caughtNot applicable
C: comparison with OpenSSL (20,000 digests and MACs)All matchNot applicable
C++: build and tests, C++17 and C++20g++ 13.3 and Clang 18, all vectors pass, 19 of 19 mutants caughtMSVC, C++17 and C++20, all tests pass
Java: build and testsOpenJDK 21 with --release 17, -Xlint:all -Werror, all passCompiled with --release 17, all vectors pass
Python: tests, ruff, mypyPython 3.13, all passAll tests pass
C#: build and tests.NET 8 SDK on a net8.0 copy of the project, all passAll tests pass
Demo, collision, length-extension and pitfall outputMatches tests/expected/Matches tests/expected/ in the C and C++ test runs
BenchmarkRun on the cloud container described aboveNot run

Not covered: 32-bit builds, big-endian machines, macOS, Java 17 and 25, .NET 10 (the C# project targets it, but the local run used the .NET 8 SDK), the GitHub Actions workflows themselves and side-channel timing. The SHA-3 and SHA-512/256 statements come from published references and were not run here.

Scroll to Top