Skip to content

Checksums & Hashing: Parity, CRC32/CRC32C, xxHash, Murmur, SHA-2/3, BLAKE3, Content Addressing ​

"The hash algorithms specified in this Standard are called secure because, for a given algorithm, it is computationally infeasible 1) to find a message that corresponds to a given message digest, or 2) to find two different messages that produce the same message digest." — NIST, FIPS 180-4 Secure Hash Standard (SHS), 2015

Summary: A "hash" is three different tools under one name: checksums catch accidents, fast hashes spread keys, cryptographic hashes stand up to attackers, and none of them replaces the others. Focus: Parity, Adler-32, CRC-32/CRC-32C, xxHash/XXH3, Murmur, SipHash, MD5/SHA-1/SHA-2/SHA-3/BLAKE3, HMAC, content addressing, ETags, end-to-end upload checksums and bit rot, with measured speeds and Go + Laravel code. Learning goal: For any byte stream in your system, name the threat (noise, skew or attacker), pick the right function and output size, and verify it at the right place: on the wire, at rest, and end to end.

This page is the complete reference for integrity and fingerprinting of bytes. It covers every family a backend engineer meets (parity, Fletcher, Adler-32, the Internet checksum, CRC-32, CRC-32C, CRC-64/NVME, FNV, MurmurHash3, CityHash, FarmHash, xxHash, XXH3, SipHash and Go's seeded map hash, MD5, SHA-1, SHA-2, SHA-3/Keccak, BLAKE2, BLAKE3), the properties that separate them (Hamming distance, avalanche, preimage, second preimage, collision, length extension), and the places they live in production: Ethernet, gzip, PNG, iSCSI, Kafka record batches, PostgreSQL data pages, ZFS and btrfs, S3 checksums and ETags, git objects, Docker/OCI digests, Nix, IPFS, HTTP ETags and Subresource Integrity. Neighbours are linked, not re-taught: hex and base64 are in Binary-to-Text Encoding; gzip and zstd framing in Compression; HMAC internals, AEAD, signatures and KDFs in Cryptography Fundamentals; salts, bcrypt and Argon2 in Password Hashing & Signed Tokens; the TLS record layer in TLS in Practice; Bloom filters in Bloom Filters & Probabilistic Structures; hash rings in Consistent Hashing; and the Go crypto/* API tour in Go: Hashing & Crypto.

Page map ​

If you are looking forGo to
Three tables to memorise in one minuteEverything in one minute
Why one function cannot do all three jobsWhy it exists
Parity to BLAKE3, SHAttered, NIST retiring SHA-1Where it comes from
One block per family with plain words, misunderstanding, scenarios, per-product tableThe concept catalogue
CRC long division, polynomials, hardware instructionsCRC-32 and CRC-32C, Mechanics: CRC by hand
xxHash, Murmur, FNV, CityHash, SipHash, hash floodingNon-cryptographic hashes, SipHash and seeded hashes
Preimage, collision, length extension, Merkle–Damgård vs spongeCryptographic properties, SHA-2 and length extension
git, Docker/OCI digests, Nix, IPFS CID, S3 ETag quirksContent addressing
ETag, If-None-Match, 304ETags and conditional requests
TCP checksum weakness, TLS AEAD, x-amz-checksum-*, rsyncIn transit vs at rest
ZFS, btrfs, PostgreSQL data_checksums, scrubbingBit rot and silent corruption
Hex vs base64 sizes, truncation, birthday bound tableOutput sizes, encodings, truncation, Birthday bound
MB/s for each algorithm on a real machinePerformance you measure
Hex dumps of a gzip trailer, a git object, an OCI layerByte-level view
Upload verification, dedup, download verification, webhooks, ETags, sharding, scrubbingSolving the classic problems
Which function for which jobChoosing
Monolith to multi-regionIn architecture
Error messages and what they meanTroubleshooting
Flip a bit, stream-hash an upload, verify a Docker digest and a git object by handLab

Everything in one minute ​

The three jobs. Every row is unpacked in the catalogue.

JobThreatTypical functionsOutputWhere you meet it
Detect accidental corruptionRandom bit flips, bursts, bad RAM/disk/cableParity, Adler-32, CRC-32, CRC-32C, CRC-64/NVME1–64 bitsEthernet FCS, gzip, zip, PNG, iSCSI, Kafka batches, PostgreSQL pages, btrfs, S3
Fingerprint and bucket fastSkewed keys, slow code, hash floodingFNV-1a, MurmurHash3, CityHash/FarmHash, xxHash64, XXH3, SipHash, Go maphash32–128 bitsHash tables, Bloom filters, shard routing, dedup pre-check, Laravel ETags
Integrity against an adversaryA person crafting colliding or modified inputSHA-256, SHA-512, SHA-3, BLAKE2, BLAKE3256–512 bitsgit, Docker/OCI digests, download checksums, SRI, signatures
Authenticity (who sent it)Attacker who can also recompute any unkeyed hashHMAC-SHA256, keyed BLAKE3, signatures256 bitsWebhooks, signed URLs, cookies, JWT (HS256)

The algorithms at a glance (speeds measured on an Apple M5, one goroutine, Go; see Performance).

AlgorithmFamilyBitsMB/s hereUse forNever use for
CRC-32 (IEEE)Checksum32~11 000zip/gzip/PNG compatibilityAnything an attacker touches
CRC-32CChecksum32~11 900New storage/network formatsDedup keys (too short)
Adler-32Checksum32~4 100zlib streamsShort messages (weak)
FNV-1a 64Fast hash64~1 100Tiny keys, simple codeLarge data, untrusted keys
MurmurHash3Fast hash32/128~9 200Cassandra-style partitioning, Bloom filtersSecurity
XXH3 / XXH128Fast hash64/128~36 000Cache keys, ETags, dedup pre-checkSecurity
SipHash / maphashKeyed fast hash64n/aIn-memory hash tables with untrusted keysPersistent IDs
MD5Broken crypto128~920Legacy fingerprints, S3 Content-MD5Signatures, anything adversarial
SHA-1Broken crypto160~3 400Legacy git idsNew designs
SHA-256Crypto (MD)256~3 400Default content address, OCI, signaturesRaw H(key‖msg) MACs
SHA-512Crypto (MD)512~2 00064-bit CPUs without SHA-256 instructionsSame
SHA3-256Crypto (sponge)256~1 100Diversity from SHA-2, FIPSSpeed-critical paths
BLAKE2bCrypto256/512~1 450libsodium generichash, btrfs—
BLAKE3Crypto (tree)256+~1 000 (pure Go on arm64)Big files with SIMD, parallel hashingInterop with tools that expect SHA-256

The three rules.

SituationDo this
Only nature can corrupt the bytes (disk, network, RAM)CRC-32C or XXH3, checked at every hop, plus an end-to-end check
Someone could choose the bytesSHA-256 (or BLAKE3); compare digests in constant time
You must know who produced the bytesA key: HMAC-SHA256 or a signature. An unkeyed hash, of any strength, proves nothing about origin

Why it exists ​

Every byte you store or send crosses something that can damage it: a cable, a NIC buffer, a RAM cell, a disk sector, a buggy firmware, a proxy that "helpfully" rewrites line endings. Without a check, the damage is silent: the program reads the wrong byte and continues. A checksum adds a few redundant bits so the receiver can notice. Separately, programs need to turn arbitrary keys into small numbers fast (hash tables, sharding), and security needs a fingerprint nobody can forge. These are three different problems with three different enemies, and the design that is optimal for one is wrong for the other two.

Faster, smaller (checksums, fast hashes)Stronger, bigger (cryptographic hashes)
10–40 GB/s per core, often one CPU instruction1–3.5 GB/s per core on the same machine
32–64 bits of output256–512 bits
Mathematically guaranteed to catch specific error patterns (CRC: all bursts up to 32 bits)No guarantee for any specific pattern; only "infeasible to find a collision"
Linear or easy to invert: an attacker can fix the checksum after editingNo known way to make two inputs match
Output designed to fit a table index or a header fieldOutput designed to name content globally

The analogy we reuse on this page: a parcel. A checksum is the weight printed on the label: if the parcel arrives lighter, something fell out on the road, but a thief can replace the contents with something of the same weight. A fast hash is the shelf number the warehouse computes from the address so parcels spread evenly across shelves; it says nothing about the contents. A cryptographic hash is a tamper-evident seal whose pattern depends on every item inside: nobody can repack the box to match. HMAC is that seal stamped with your private stamp: it also proves the parcel came from you.

Three common misunderstandings, up front ​

  1. "SHA-256 makes my data secure." A hash proves the bytes match a digest you already trust. If the attacker can replace both the file and the published digest (same server, same HTTP response), the check passes. Authenticity needs a key or a signature, or the digest must arrive over a channel the attacker cannot touch.
  2. "CRC-32 is just a weak hash." CRC is not a weak hash; it is a strong error-detecting code with guarantees no cryptographic hash offers (every burst of 32 bits or fewer is detected). It is useless against people because it is linear.
  3. "TCP and TLS already check everything, so my upload is safe." They protect one hop. Bytes are decrypted and re-encrypted at load balancers, buffered in RAM, written by drivers and read back by other services. Only a digest computed by the producer and checked by the final consumer covers the whole path. Amazon S3 asks for exactly that.

Where it comes from ​

text
1961   Peterson & Brown, "Cyclic Codes for Error Detection" (the CRC family; per Wikipedia, secondary)
1988   RFC 1071: computing the Internet (ones' complement) checksum
1992   MD5 (RFC 1321, April 1992)
1993   Castagnoli et al. search 47 000 polynomials; the best becomes CRC-32C (per RFC 3385)
1995   SHA-1 in FIPS 180-1 (per NIST)
1996   RFC 1950/1952: zlib uses Adler-32 (a Fletcher variant), gzip uses CRC-32
1997   RFC 2104: HMAC
2002   RFC 3385 analyses CRC32C for iSCSI; RFC 3720 (2004) adopts it
2003   Crosby & Wallach: hash-flooding attacks (per the SipHash paper)
2011   December: hash flooding shown against many web languages at once (per the SipHash paper)
2012   SipHash paper (Aumasson & Bernstein)
2015   FIPS 180-4 (SHA-2 family) and FIPS 202 (SHA-3, Keccak sponge)
2017   SHAttered: first practical SHA-1 collision (per git's hash-function-transition)
2018   git picks SHA-256 as its successor hash ("In late 2018")
2022   NIST: phase SHA-1 out by Dec. 31, 2030
2025   PostgreSQL 18: "Change initdb default to enable data checksums"

The checksum line and the cryptographic line grew apart for good reasons. Error-detecting codes came from communications engineering: the question was "what is the probability an undetected error slips through on this channel?", answered with algebra. RFC 3385, written to choose iSCSI's checksum, states the goal plainly: "The most important expectation from this kind of code is a very low probability for undetected errors." Cryptographic hashes came from the need to sign long documents with slow public-key operations: you sign a short digest, so the digest must be impossible to collide. FIPS 180-4 names those two properties in the quote at the top of this page. The fast non-cryptographic hashes (Murmur, CityHash, xxHash) came later still, from the hash-table and big-data world, where neither guarantee matters as much as speed and an even spread.

Dates for SHAttered and git's SHA-256 choice come from git's own hash-function-transition document; the 2030 date comes from NIST's announcement: "NIST is announcing that SHA-1 should be phased out by Dec. 31, 2030, in favor of the more secure SHA-2 and SHA-3 groups of algorithms." The PostgreSQL default comes from the initdb reference: data checksums are "enabled by default; use --no-data-checksums to disable checksums."

One word "hash", three different jobs1. Detect accidentsenemy: noise, bad RAM, bad diskParity (1 bit)Fletcher, Adler-32CRC-32 (IEEE), CRC-32CCRC-64/NVMEWhereEthernet FCS, gzip, zip, PNGiSCSI, Kafka batches, ext4Postgres pages, btrfs, S3Guaranteeall bursts up to 32 bits caught2. Fingerprint and bucketenemy: skewed keys, slow codeFNV-1a, MurmurHash3CityHash, FarmHashxxHash64, XXH3, XXH128SipHash, Go maphash (seeded)Wherehash tables, Bloom filtersshard routing, dedup pre-checkETags, cache keys (non-secret)Guaranteegood spread, tens of GB/s3. Resist an adversaryenemy: a person crafting inputsSHA-256, SHA-512SHA-3 / Keccak, SHAKEBLAKE2b, BLAKE3(MD5, SHA-1: broken)Wheregit objects, OCI image digestsdownload checksums, SRIsignatures sign a digestGuaranteecollisions infeasible to find+ secret key = authenticationHMAC, keyed BLAKE3, signaturesfaster, smaller, no securityslower, bigger, safe against people

The concept catalogue ​

Each block: plain words, the usual wrong belief, a precise definition, a step-by-step sequence where it helps, real scenarios, per-product behaviour, and the fix (code is collected in Solving the classic problems).

Parity Good to know ​

In plain words: one extra bit that makes the count of 1-bits even (or odd). If one bit flips, the count is wrong.

Common misunderstanding: "Parity catches corruption." It catches any odd number of flipped bits and misses every even number: two flips cancel out.

Definition: the XOR of all data bits. Detects all single-bit errors, no double-bit errors. RFC 1071 already dismissed plain XOR for packets: "XOR takes the minimal amount of computer time to generate and check, but is not a good checksum."

Real scenarios: serial links, RAID 5 parity (XOR across disks used for reconstruction, not detection of silent errors), the parity row in our bit-flip lab.

Where (per Wikipedia, secondary)What it really is
Serial links (UART)Optional parity bit per character
RAID 5A parity stripe across disks; when a disk reports a read error, its data is rebuilt from the others; "A single parity bit, by itself, cannot perform error correction"
ECC RAMStronger codes than plain parity, so single-bit errors are corrected, not only detected

Fix: use it only as a teaching device; real systems use CRC or ECC.

Fletcher and Adler-32 Good to know ​

In plain words: two running sums. The first adds the bytes; the second adds the first sum after every byte, so the position of each byte matters, not only its value.

Common misunderstanding: "Adler-32 is a faster CRC-32 with the same quality." It is weaker, especially for short messages: the sums do not fill 32 bits until a few hundred bytes have passed. RFC 3385's comparison table puts CRC32C ahead of both: for its error model: "For independent bit errors, Pud of CRC is approximately 12,000 better than Fletcher, and 22,000 better than Adler."

Definition (RFC 1950): "Adler-32 is composed of two sums accumulated per byte: s1 is the sum of all bytes, s2 is the sum of all s1 values. Both sums are done modulo 65521." Fletcher uses modulo 255 or 65535; Adler picked the prime 65521 because, in RFC 1950's words, Fletcher's modulus "is not prime and which also makes the Fletcher check insensitive to single byte changes 0 <-> 255."

Real scenarios: every zlib stream (and therefore every PNG IDAT and HTTP Content-Encoding: deflate body) ends with Adler-32; ZFS's default fletcher4 block checksum; rsync's weak rolling checksum is an Adler-style sum.

ProductChecksumNote
zlib (RFC 1950)Adler-32 of uncompressed datagzip wraps the same deflate data with CRC-32 instead
ZFSfletcher4 (checksum=on)sha256 is the default for deduplicated datasets
rsync32-bit rolling sum + strong hashSee rsync

Fix: keep them where formats require them; choose CRC-32C for anything new.

CRC-32 and CRC-32C Must-know ​

In plain words: treat the message as one enormous binary number, divide it by a fixed "generator" number using XOR instead of subtraction, and keep the remainder. Append the remainder; the receiver divides again and expects zero.

Common misunderstanding: "All CRC-32s are the same." There are dozens. The two you meet are CRC-32 (IEEE 802.3, generator 0x04C11DB7, reflected 0xEDB88320), used by Ethernet, gzip, zip and PNG, and CRC-32C (Castagnoli, 0x1EDC6F41, reflected 0x82F63B78), used by iSCSI, ext4, btrfs, Kafka and Google Cloud Storage. Same length, different polynomial, different values, different strength. PHP adds a third: hash('crc32') is the BZIP2 variant, while hash('crc32b') is the zip one.

Definition: a cyclic redundancy check of degree r is the remainder of M(x)·x^r divided by a generator polynomial G(x) over GF(2), the field with two elements where addition is XOR. Its strength is measured by Hamming distance (HD): the minimum number of flipped bits that can go undetected, for a given message length. An r-bit CRC with a factor (x+1) detects every odd number of errors and every burst error of length ≤ r. RFC 3385 summarises the Castagnoli search: "The best they found has d=6 up to block lengths of 5275 and d=4 up to 2^31-1 (bits)," against "the IEEE-802 code has d=4 up to at least 64,000 bits ... and d=3 up to 2^32-1 bits." In plain numbers: CRC-32C misses no error of up to 5 flipped bits in messages up to 5 275 bits and no error of up to 3 bits in messages up to 2^31−1 bits; CRC-32 (IEEE) guarantees HD=4 only up to about 64 000 bits and HD=3 beyond.

Sequence: what a CRC does on the wire.

text
1  sender   : frame bytes -> CRC unit (shift + XOR per bit, or one CRC32 instruction per 8 bytes)
2  sender   : append 4-byte FCS (Ethernet) / write crc field (Kafka batch header)
3  network  : one bit flips in transit
4  receiver : recompute CRC over data -> 0x5667c7f9, stored value says 0x414fa339
5  receiver : mismatch -> drop frame (Ethernet) / CorruptRecordException (Kafka) / retry

Hardware. x86 SSE4.2 has a CRC32 instruction that computes CRC-32C (the Castagnoli polynomial only); ARMv8 has instructions for both polynomials. Go's hash/crc32 uses them: on this arm64 machine crc32_arm64.s issues CRC32CX, and both polynomials run at 11–12 GB/s; on amd64, crc32_amd64.go calls "the SSE 4.2 version of the Castagnoli" CRC and uses carry-less multiplication for IEEE. Go's doc comment is worth remembering: Castagnoli "Has better error detection characteristics than IEEE."

CRC = remainder of a long division where subtraction is XORSender: message 11010011101100, generator 1011 (x³+x+1)11010011101100 000 ← 3 zero bits appended1011 ← XOR where the lead bit is 101100011101100 000 101100111011101100 000 101100010111101100 000 1011 … 5 more XOR steps …00000000000000 100 ← remainder = CRCNo carries, no borrows: each step is one shift and one XOR,which is why hardware (and one CPU instruction) does it fast.Transmit message + remainder11010011101100 100Receiver divides the whole thing by 1011.Remainder 000 → accept.Anything else → corrupted, drop or retry.Real CRC-32 is the same idea, plus:33-bit generator: 0x104C11DB7 (IEEE)or 0x11EDC6F41 (Castagnoli, CRC-32C)bits processed LSB-first (reflected)init 0xFFFFFFFF, final XOR 0xFFFFFFFFcheck("123456789") = cbf43926 / e3069283Linear, so not a security toolcrc(a ⊕ b) = crc(a) ⊕ crc(b) ⊕ crc(0…0): an attacker can change data and fix the CRC without any key

Real scenarios: a flaky NIC or cable corrupting frames (Ethernet FCS drops them and the NIC's CRC-error counter climbs); a gzip download that fails with "crc error" after a proxy truncated it; a Kafka broker that refuses a batch from a client with bad RAM; Postgres replicas that fail a checksum because of a faulty SAN controller.

Product / formatCRCCovers
Ethernet (IEEE 802.3) FCSCRC-32Each frame
gzip (RFC 1952)CRC-32Uncompressed data, in the 8-byte trailer with ISIZE
zipCRC-32Each file entry
PNGCRC-32Each chunk's type and data
iSCSI (RFC 3720)CRC-32CHeader and data digests
ext4 (metadata_csum), btrfsCRC-32Cext4: metadata only; btrfs: data and metadata by default
Kafka record batch (v2)CRC-32CFrom attributes to end of batch
PostgreSQL data pages16-bit page checksum "based on the FNV-1a hash" (checksum_impl.h)Each 8 KiB page (not a CRC; see bit rot)
PostgreSQL WAL recordsCRC-32C (pg_crc32c xl_crc)Each WAL record
Amazon S3CRC-64/NVME (default), CRC-32, CRC-32C, SHA-1, SHA-256, MD5, XXHash64/3/128, SHA-512Object, per part, or composite
Google Cloud StorageCRC-32C and MD5 (Flysystem lists "md5, crc32c, etag")Object

Kafka's own protocol doc is explicit: "The CRC-32C (Castagnoli) polynomial is used for the computation," and it also explains why the partition leader epoch is outside the CRC: "to avoid the need to recompute the CRC when this field is assigned for every batch that is received by the broker."

Fix: use CRC-32C for new formats; store it next to the data it covers; verify on every read. The Go and PHP code is in Mechanics: CRC by hand and Checksums.php.

The Internet checksum (IP, TCP, UDP) Important ​

In plain words: add up the packet as 16-bit numbers (with end-around carry) and send the complement. Cheap enough for 1980s routers.

Common misunderstanding: "TCP guarantees my bytes are correct." TCP guarantees that the 16-bit sum matches. Any reordering of 16-bit words, and many pairs of compensating errors, give the same sum.

Definition (RFC 9293, TCP): "The checksum field is the 16-bit ones' complement of the ones' complement sum of all 16-bit words in the header and text." RFC 3385 cites measurements showing "a serious weakness of the checksums on real-data", because such sums do not spread the hot spots in the input.

Real scenarios: NIC checksum-offload bugs; middleboxes rewriting payloads and recomputing the sum; the [Stone98] measurements on real traffic cited by RFC 3385. In practice Ethernet's CRC catches most link errors, but errors inside routers, NICs and host memory happen after the CRC is checked and before TCP's weak sum.

LayerCheckStrength
EthernetCRC-32 per frame, per hopStrong, but stripped and recomputed at every hop
IPv4 header16-bit ones' complement, header onlyWeak
TCP / UDP16-bit ones' complement over pseudo-header + dataWeak
TLS 1.3 recordAEAD tag (AES-GCM, ChaCha20-Poly1305)Cryptographic, per TLS session only

Fix: do not rely on it. TLS gives you cryptographic integrity per connection; an application digest gives you end to end. See In transit vs at rest.

Non-cryptographic hashes: FNV, MurmurHash3, CityHash/FarmHash, xxHash/XXH3 Must-know ​

In plain words: turn any key into a well-mixed number as fast as possible, so items spread evenly over buckets, shards or bits.

Common misunderstanding: "A 64-bit xxHash is as good as SHA-256 for deduplication, just faster." For random data, collisions are as rare as the birthday bound says. But nobody has to search for an MD5-style attack: anyone who can upload two files can deliberately create an xxHash collision, because the function was never designed to resist that. CityHash's README says it in one line: "The functions mix the input bits thoroughly but are not suitable for cryptography."

Definition: a function with good avalanche (flipping one input bit flips about half of the output bits) and uniform distribution, tested with suites like SMHasher, "a test suite designed to test the distribution, collision, and performance properties of non-cryptographic hash functions." The xxHash README describes XXH3 as the current default: "For new applications, XXH3_64bits() is the recommended default. Use XXH3_128bits() when a 128-bit hash is required."

HashBitsOriginWhere you meet it
FNV-1 / FNV-1a32/64Fowler–Noll–Vo, very simple loopGo hash/fnv, PHP fnv1a64, PostgreSQL's page checksum is FNV-1a based; xxHash's table notes FNV64 has "Poor avalanche properties"
MurmurHash332/128Austin Appleby, SMHasherCassandra ("The default partitioner is the Murmur3Partitioner"), many Bloom filters, PHP murmur3a/c/f (8.1+)
CityHash / FarmHash32/64/128GoogleC++ reference code; CityHashCrc128() even uses the CRC32 instruction for mixing
xxHash6464Yann Colletzstd frame checksum (RFC 8878 uses XXH64), btrfs xxhash, rsync xxh64, Go cespare/xxhash/v2
XXH3 / XXH12864/128xxHash v0.8.0+Laravel ETags (xxh128), S3 XXHASH3/XXHASH128, rsync xxh3/xxh128, PHP 8.1+ hash('xxh3'), Go zeebo/xxh3

Real scenarios: Laravel's cache.headers middleware hashes response bodies with xxh128 for the ETag; a Go service routes user:42 to one of 8 Redis shards with XXH3 modulo (and learns about consistent hashing when it adds a ninth); a backup tool groups chunks by XXH3 and confirms duplicates with SHA-256; a Bloom filter derives k bit positions from two Murmur3 halves (Bloom filters).

Fix: use XXH3 for speed when inputs are trusted or when collisions only cost a cache miss; switch to a keyed hash for in-memory tables fed by users (next block); switch to SHA-256 when a collision would let someone read or overwrite another user's data.

SipHash, seeded hashes and hash flooding Important ​

In plain words: if an attacker knows your hash table's function, they send thousands of keys that all land in one bucket, and every insert becomes a linear scan. The defence is a secret random seed per process (or per table), so the attacker cannot predict buckets.

Common misunderstanding: "Go maps use SipHash like Rust." They do not. Rust's HashMap default "is currently SipHash 1-3", chosen "to provide resistance against HashDoS attacks." Go's runtime uses an AES-based hash when the CPU has AES instructions and a wyhash-inspired fallback otherwise, with a per-map random seed; the source comment in internal/runtime/maps/map.go says: "seed is the hash seed, computed as a unique random number per map."

Definition: SipHash (Aumasson & Bernstein, 2012) is a keyed pseudorandom function fast enough for short keys; its paper frames the use case as "hash-table lookups protected against hash-flooding denial-of-service attacks." Hash flooding / HashDoS is the attack. The paper's history: "Crosby and Wallach reintroduced the same attack in 2003", and it surfaced "again in December 2011" against many web platforms.

text
1  attacker : precompute 50 000 form-field names with equal hash under the server's known function
2  attacker : POST them in one request body
3  server   : parse body into a hash table -> every insert collides -> O(n²) CPU
4  server   : one request pins a core for seconds; a few hundred requests take the service down
5  fix      : random per-process/per-table seed (SipHash, maphash, AES hash) + max_input_vars style limits
Language / runtimeDefault table hashSeeded?
Go mapAES hash (amd64/arm64 with AES) or wyhash-style fallbackYes, random per map
Go hash/maphashSame runtime hash, exposedYes: maphash.MakeSeed(); "The hash functions are not cryptographically secure"
Rust HashMapSipHash 1-3 (RandomState)Yes, random per process
Python dict (str/bytes)SipHash (PEP 456: "SipHash ... is introduced as default hash algorithm")Yes, random per process
PHP arraysDJBX33A, "Times 33 with Addition" (zend_string.h)No; PHP limits request input instead (max_input_vars, default 1000)
Java HashMaphashCode() of the keyNo; a bucket becomes a balanced tree at TREEIFY_THRESHOLD = 8

Fix: never persist or share a seeded hash (it changes every run: our shard program prints a different maphash value each time); for stable shard routing use a fixed function like XXH3; for user-controlled keys in memory, rely on the runtime's seeded map.

Cryptographic hash properties Must-know ​

In plain words: a cryptographic hash is a fingerprint where nobody can work backwards from the fingerprint, nobody can make a second item with your item's fingerprint, and nobody can make any two items with the same fingerprint.

Common misunderstanding: "Collision resistance and second-preimage resistance are the same thing." A collision attack lets the attacker choose both inputs (much easier: birthday bound, ~2^(n/2) work). A second-preimage attack must match your existing input (~2^n work). MD5 and SHA-1 are broken for collisions but still not practically broken for preimages, which is why git's transition doc talks about collision and second-preimage needs separately.

Definition:

PropertyAttacker's taskGeneric cost for n-bit outputMD5 (128)SHA-1 (160)SHA-256
Preimage resistanceGiven digest d, find any m with H(m)=d2^nNot practically brokenNot practically brokenIntact
Second-preimage resistanceGiven m1, find m2≠m1 with H(m1)=H(m2)2^nNot practically brokenNot practically brokenIntact
Collision resistanceFind any m1≠m2 with H(m1)=H(m2)2^(n/2)Broken (practical)Broken (SHAttered 2017)Intact (2^128)
AvalancheOne-bit change flips ~50% of output—YesYesYes (our lab: 123/256 bits)

Real scenarios: two PDFs with the same SHA-1 let a signature on one be moved to the other (SHAttered's demonstration); a user uploads two MD5-colliding files to a service that dedups by MD5 and one user's file is served to the other; a download mirror replacing a binary would need a preimage, still infeasible, so a SHA-256 checksum from a trusted channel works.

Fix: SHA-256 or BLAKE3 for anything adversarial; never accept MD5/SHA-1 where an attacker chooses the content.

MD5 and SHA-1 Must-know ​

In plain words: two older cryptographic hashes that are now broken for collisions. They still work as fingerprints when nobody is attacking.

Common misunderstanding: "MD5 is broken, so remove it everywhere." RFC 6151's guidance is narrower: "MD5 is no longer acceptable where collision resistance is required such as digital signatures. It is not urgent to stop using MD5 in other ways, such as HMAC-MD5; however, ... new protocol designs should not employ HMAC-MD5." Using MD5 as S3 Content-MD5 to catch network corruption is fine; using it as the dedup key for user uploads is not, because a user can upload two colliding files.

Definition: MD5: 128-bit Merkle–Damgård, 1992. SHA-1: 160-bit Merkle–Damgård, FIPS 180-1, 1995. Git's transition document: "On 23 February 2017 the SHAttered attack ... demonstrated a practical SHA-1 hash collision." Git responded first with collision detection ("Git v2.13.0 and later subsequently moved to a hardened SHA-1 implementation by default"), then with SHA-256 repositories.

ProductMD5 / SHA-1 use todaySafe?
git (default repos)SHA-1 object ids, "hardened SHA-1" with collision detectionAcceptable; SHA-256 repos available (git init --object-format=sha256)
Amazon S3Content-MD5, ETag of single-part objectsYes, as corruption detection
PostgreSQLmd5() functionFine for non-adversarial fingerprints
Digital signatures, certificatesMD5/SHA-1 digestsNo (RFC 6151, NIST)
HMAC-MD5 / HMAC-SHA1 (old APIs)Still not practically forgeableLegacy only

Fix: keep MD5/SHA-1 only for compatibility and non-adversarial fingerprints; everything new uses SHA-256 or better.

SHA-2, Merkle–Damgård and length extension Must-know ​

In plain words: SHA-256 chops the message into 64-byte blocks and feeds them one by one into a compression function, carrying a 32-byte state forward. The final state is the digest.

Common misunderstanding: "sha256(secret + message) is a fine signature." Because the digest is the full internal state, an attacker who knows sha256(secret + message) and the length of secret can continue hashing from that state and produce a valid sha256(secret + message + padding + extra) without knowing the secret. This is the length extension attack, and it is the reason HMAC exists.

Definition: SHA-224/256 (32-bit words, 64-byte blocks) and SHA-384/512, SHA-512/224, SHA-512/256 (64-bit words, 128-byte blocks), FIPS 180-4. The Merkle–Damgård construction pads the message with a 1 bit, zeros and the 64- or 128-bit length, then iterates the compression function. Truncated variants (SHA-384, SHA-512/256) do not expose the full state and resist length extension. BLAKE3's README advertises being "secure against length extension, unlike SHA-2."

text
1  server   : tag = sha256(SECRET || "user=alice&role=user")        (naive MAC)
2  attacker : knows tag, guesses len(SECRET) = 16
3  attacker : state = tag; continue compression over padding || "&role=admin"
4  attacker : sends "user=alice&role=user" || padding || "&role=admin" with new tag
5  server   : sha256(SECRET || that) == new tag -> accepts role=admin
6  fix      : HMAC-SHA256(SECRET, msg) (two nested hashes), or SHA-512/256, SHA-3, BLAKE3 keyed mode

Real scenarios: any home-made "signed URL" or API signature built as md5($secret.$query) or sha256($secret.$body); cookies "signed" by appending a hash of secret plus value.

FunctionConstructionLength extension?
MD5, SHA-1, SHA-256, SHA-512Merkle–Damgård, full state outputVulnerable
SHA-384, SHA-512/256Merkle–Damgård, truncated outputResistant
SHA-3, SHAKESponge, capacity never outputResistant
BLAKE2, BLAKE3Finalization flags; BLAKE3 is a treeResistant
HMAC-anythingNested keyed hashResistant

Fix: use HMAC (crypto/hmac, hash_hmac) for keyed integrity. See HMAC.

SHA-3, Keccak and SHAKE: the sponge Important ​

In plain words: instead of a chain of compression steps, SHA-3 keeps a big 1600-bit state. It XORs input into part of it (the rate), stirs everything with a permutation, and repeats; to output, it reads from the rate part. The other part (the capacity) is never exposed, so attackers never see the full state.

Common misunderstanding: "SHA-3 replaced SHA-2 because SHA-2 is broken." SHA-2 is not broken; NIST's SHA-1 announcement recommends moving "in favor of the more secure SHA-2 and SHA-3 groups", side by side. SHA-3 is a structurally different design. FIPS 202 calls these functions "sponge functions" and specifies SHA3-224/256/384/512 plus the extendable-output functions (XOF) SHAKE128 and SHAKE256, which produce as many bytes as you ask for.

Definition: the Keccak-f[1600] permutation over a 1600-bit state; for SHA3-256 the capacity is 512 bits (twice the output) and the rate is the remaining 1088 bits. The capacity is what keeps the internal state hidden, so length extension does not apply.

WhereFunction
Gocrypto/sha3 (new in Go 1.24): sha3.New256(), sha3.NewSHAKE256()
PHPhash('sha3-256', ...)
PostgreSQLpgcrypto digest(): md5, sha1, sha224–sha512 "Moreover, any digest algorithm OpenSSL supports"

Fix: choose SHA-3 when a standard requires it or you want diversity from SHA-2; it is slower in software (~1.1 GB/s here).

BLAKE2 and BLAKE3 Important ​

In plain words: modern cryptographic hashes designed to be as safe as SHA-3 and faster than MD5 in software. BLAKE3 is a Merkle tree inside, so it can use every core and SIMD lane.

Common misunderstanding: "BLAKE3 is always faster than SHA-256." The README's claim, "Much faster than MD5, SHA-1, SHA-2, SHA-3, and BLAKE2", holds for its optimised C/Rust implementation with SIMD on x86. On our arm64 machine, the Go package github.com/zeebo/blake3 has assembly only for amd64 (SSE4.1/AVX2), so it runs in pure Go at ~1 GB/s, while SHA-256 uses the ARMv8 SHA256H instructions at ~3.4 GB/s. Measure on your hardware.

Definition: BLAKE2b (64-bit, up to 512-bit output) and BLAKE2s (32-bit, up to 256-bit), RFC 7693; BLAKE3 splits input into 1 KiB chunks, hashes them as leaves of a binary tree, and is also "A PRF, MAC, KDF, and XOF, as well as a regular hash." Tree hashing enables verified streaming (check each chunk as it arrives) and parallelism.

ProductUses
libsodium / PHP sodium_crypto_generichashBLAKE2b
WireGuardBLAKE2s ("BLAKE2s [2] for hashing", whitepaper)
btrfsblake2 (BLAKE2b-256) checksum option
Argon2 (RFC 9106, password hashing)BLAKE2b inside
Gogolang.org/x/crypto/blake2b, blake2s; github.com/zeebo/blake3

Fix: BLAKE3 for large local files on x86 with SIMD, or when you want a keyed mode without HMAC; SHA-256 when interop matters (OCI, S3, SRI, git).

HMAC and keyed hashing Must-know ​

In plain words: mix a secret key into the hash so only key holders can produce or check the tag. Integrity and authenticity.

Common misunderstanding: "Integrity and authentication are the same." A SHA-256 digest proves bytes did not change relative to a digest you trust. An HMAC proves bytes came from someone who holds the key. Webhooks, signed URLs and cookies need the second.

Definition (RFC 2104): "HMAC, a mechanism for message authentication using cryptographic hash functions." HMAC(K, m) = H((K ⊕ opad) ‖ H((K ⊕ ipad) ‖ m)). The outer hash hides the inner state, which defeats length extension. Compare tags in constant time (hmac.Equal, hash_equals). PHP's hash_init docs note that non-cryptographic algorithms "with HASH_HMAC was disabled" (since PHP 7.2). Key management, HKDF and signatures are in Cryptography Fundamentals; signed URLs and JWT HS256 in Password Hashing & Signed Tokens.

text
1  sender   : body = {"amount":1000}; ts = 1764090000
2  sender   : sig  = HMAC-SHA256(secret, ts + "." + body); headers X-Timestamp, X-Signature
3  receiver : reject if |now - ts| > 300 s (replay window)
4  receiver : expected = HMAC-SHA256(secret, ts + "." + raw body)   -- raw bytes, never re-encoded JSON
5  receiver : hash_equals(expected, sig) ? accept : 401
MechanismIntegrityAuthenticityNon-repudiation
CRC / xxHashAgainst accidentsNoNo
SHA-256 (published digest)Against attackers, if digest channel is trustedNoNo
HMAC-SHA256YesYes (shared key)No (both sides can sign)
Ed25519 / RSA signature over SHA-256YesYesYes
AEAD tag (AES-GCM, ChaCha20-Poly1305)YesYes, for that session keyNo

Fix: Authenticate a webhook.

Content addressing Must-know ​

In plain words: name a thing by the hash of its bytes. If you have the name, you can fetch the bytes from anywhere (an untrusted mirror, a cache, a peer) and check them yourself.

Common misunderstanding: "A Docker tag pins an image." A tag such as alpine:3.20 is a mutable pointer; the registry can move it at any time. Only alpine@sha256:... pins bytes. Likewise "an S3 ETag is the MD5 of the object" is often false: for multipart uploads and SSE-KMS objects it is not.

Definition: the identifier is H(canonical bytes), often with a type prefix or header so different kinds of objects cannot collide. Objects that reference other objects by digest form a Merkle DAG: the top digest commits to every byte below.

Hashes of hashes: a Merkle tree, and an image addressed by contentroot = H(1 ‖ H01 ‖ H23)H01 = H(1 ‖ H0 ‖ H1)H23 = H(1 ‖ H2 ‖ H3)H0 = H(0 ‖ c0)H1 = H(0 ‖ c1)H2 = H(0 ‖ c2)H3 = H(0 ‖ c3)chunk c0chunk c1c2: 1 bit flippedchunk c3Only the red path is recomputed; H3 and H01 are the proof that c2 belongs to the root. Same shape: BLAKE3 inside, git trees, IPFS DAGs.tag alpine:3.20mutable nameimage indexsha256:d9e853e8…arm64 manifestsha256:45e09956…config sha256:ab3fe4de… (628 B)layer .tar.gz sha256:3f26bc2d… (4 092 319 B)diff_id of the .tar: sha256:88b4fba6…Each box names its children by digest,so the top digest pins every byte below.Pull by @sha256:… and nothing can change.config lists diff_ids (gunzipped layer hash)
SystemIdentifierWhat is hashedQuirk
gitSHA-1 (or SHA-256) hex, 40 (64) chars"blob <size>\0" + content; trees and commits likewise"named with the SHA-1 checksum of the content and its header"; stored zlib-compressed in .git/objects/xx/yyyy…
Docker / OCIsha256:<64 hex>Exact bytes of manifest, config, or compressed layerLayer digest hashes the .tar.gz; the config's diff_ids hash the uncompressed .tar
Nix32-char base32 hash part of /nix/store/<hash>-nameDerivation inputs (input-addressed) or output (content-addressed)"A 20-byte digest for identification", rendered in Nix's own base32
IPFSCID (multibase + version + codec + multihash)Each block of a chunked DAG"SHA file hashes won't match CIDs", because files are chunked
S3ETagMD5 of data only for single-part, SSE-S3/plain objectsMultipart: built from per-part MD5s, not an MD5 of the object; SSE-C/SSE-KMS: not an MD5
Build and CI caches (GitHub Actions hashFiles() in cache keys)Hash of input filesLockfiles, sourcesMissing an input in the key = stale artefacts
Your blob storesha256 column + unique indexUploaded fileDedup for free; see Deduplicate stored files

The OCI descriptor spec states the rule for consumers: "Before consuming content targeted by a descriptor from untrusted sources, the byte content SHOULD be verified against the digest string," and adds "Before calculating the digest, the size of the content SHOULD be verified to reduce hash collision space." The S3 API reference: "If an object is created by either the Multipart Upload or Part Copy operation, the ETag is not an MD5 digest, regardless of the method of encryption."

Real scenarios: Kubernetes manifests that pin image: app@sha256:… so a re-pushed tag cannot change production; a CDN serving app.3f9a1c.js with Cache-Control: immutable because the name changes when content changes; a Laravel attachments table where 4 000 users uploaded the same PDF and it is stored once.

Fix: Deduplicate stored files, and the lab verifies a Docker digest and a git object by hand.

ETags and conditional requests Important ​

In plain words: the server labels each version of a response with a short tag. The client sends the tag back; if nothing changed, the server answers "304 Not Modified" with no body.

Common misunderstanding: "ETags must be MD5s" or "ETags are security." RFC 9110: "An entity tag is an opaque validator for differentiating between multiple representations of the same resource." Any function that changes when the bytes change works; Laravel uses xxh128. A weak ETag (W/"…") means "semantically equivalent", allowed for If-None-Match on GET but not for If-Match on writes.

text
1  client -> GET /plans
2  server <- 200, ETag: "QCBtYse8ERjY9cpmOLCKuQ", Cache-Control: no-cache, body 25 bytes
3  client -> GET /plans, If-None-Match: "QCBtYse8ERjY9cpmOLCKuQ"
4  server    hash(body) unchanged -> 304 Not Modified, no body
5  client -> PUT /plans, If-Match: "QCBtYse8ERjY9cpmOLCKuQ"   (optimistic concurrency)
6  server    current tag differs -> 412 Precondition Failed (someone else changed it)
StackHow the ETag is built
Laravel cache.headers:…;etaghash('xxh128', $response->getContent()), then isNotModified()
nginx static filesetag on (default): "automatic generation of the 'ETag' response header field for static resources"
ApacheFileETag MTime Size by default: file metadata, not content
Amazon S3MD5 for simple objects, multipart form otherwise
Go http.ServeContentUses an ETag you set; handles If-None-Match, If-Match, Range

Fix: ETag and 304. For multi-server deployments, derive ETags from content (not inode or mtime), or two servers return different tags for the same bytes.

Integrity in transit vs at rest Must-know ​

In plain words: "in transit" protections check one hop and are stripped at the next. "At rest" protections live with the stored bytes. Only an end-to-end digest, computed by the producer and verified by the final consumer, covers the gaps between them.

Common misunderstanding: "HTTPS means the stored file equals the uploaded file." TLS 1.3 "only uses AEAD algorithms", so each record is authenticated, but the TLS session ends at your load balancer. After that, the bytes live in a proxy buffer, an app process and a storage client before they reach a disk.

text
1  client     : sha256(file) = ed4769b6…  -> header X-Content-SHA256 (or x-amz-checksum-sha256)
2  TLS        : AEAD tag per record, client -> load balancer  (ends here)
3  LB -> app  : plain HTTP or new TLS session; buffers in RAM
4  app        : TeeReader feeds bytes to disk AND to sha256 in one pass
5  app        : sha256 == header ? rename into place : 422 BadDigest, delete temp
6  storage    : S3 recomputes x-amz-checksum-crc64nvme / sha256 and stores it with the object
7  later read : verify again on download (ask S3 for the stored checksum) or scrub
MechanismScopeAlgorithm
Ethernet FCSOne linkCRC-32
TCP checksumOne TCP connection16-bit ones' complement
TLS 1.3One TLS sessionAEAD tag (AES-GCM, ChaCha20-Poly1305)
HTTP Content-MD5 (legacy, S3 single part)One request bodyMD5, base64
S3 x-amz-checksum-*Client to stored object (and back)CRC-64/NVME (SDK default), CRC-32, CRC-32C, SHA-1, SHA-256, MD5, XXHash*, SHA-512
HTTP Content-Digest / Repr-Digest (RFC 9530)One message / representationsha-256, sha-512
Subresource Integrity (integrity="sha384-…")CDN script to browserSHA-256/384/512, base64
rsyncEach file transferRolling sum + strong hash, negotiated with --checksum-choice (xxh128, xxh3, xxh64, md5, md4)
zfs send / receiveReplication streamFletcher4 per record

The S3 guide describes the server side: "S3 then independently calculates a checksum value of the object on the server-side, and validates it with the provided value before storing the object and checksum value," and if they differ, "S3 fails the request with a BadDigest error."

rsync's rolling checksum is the classic trick for finding moved blocks: per block it "calculates two checksums: a weak ``rolling'' 32-bit checksum ... and a strong 128-bit MD4 checksum." The weak sum can be updated in O(1) when the window slides one byte (the recurrence relations on the rsync tech report page), so every offset can be tested cheaply and only weak-sum hits pay for the strong hash. The same idea powers content-defined chunking in backup tools.

Fix: Verify an upload end to end.

Bit rot and silent corruption Important ​

In plain words: stored bits decay or get written wrong (firmware bugs, misdirected writes, bad controllers) and the disk returns them without an error. Only a checksum stored separately from the data notices.

Common misunderstanding: "RAID protects me from corruption." RAID 1/5/6 rebuilds a disk that reports failure. If a disk silently returns wrong data, a classic RAID controller does not know which copy is right. ZFS and btrfs keep a checksum per block in the parent pointer, so they know.

Definition: silent data corruption is any wrong data returned without an I/O error. Scrubbing is a periodic background read of everything to find it before you need the data. ZFS's docs list the benefits: "blocks that are detected as corrupt are automatically repaired if possible," and "periodic scrubs can check data to detect and repair latent media degradation (bit rot)."

text
1  write   : ZFS computes fletcher4(block), stores it in the parent block pointer
2  months  : one sector on disk A silently flips a bit
3  scrub   : zpool scrub reads block from disk A, checksum mismatch
4  repair  : reads mirror copy on disk B, checksum OK, rewrites disk A
5  report  : zpool status shows a non-zero CKSUM count for disk A
SystemChecksum at restRepairScrub command
ZFSfletcher4 default (checksum=on), sha256 for dedup, others per datasetFrom mirror/RAID-Z/copieszpool scrub pool
btrfscrc32c default; xxhash, sha256, blake2 (kernel 5.5+)From RAID1/DUP copiesbtrfs scrub start /mnt
ext4metadata_csum ("the only supported algorithm is crc32c") on metadata onlyNoe2fsck
PostgreSQLPer-page 16-bit checksum (FNV-1a based), enabled by default since 18No (restore from backup/replica)pg_checksums --check (offline), pg_amcheck, pg_verifybackup for backups
MySQL InnoDBinnodb_checksum_algorithm=crc32 per pageNoinnochecksum (offline)
Amazon S3Stored object checksums; S3 Batch Operations "Compute checksum"AWS internalBatch job
KafkaCRC-32C per batch; consumer check.crcs default trueRe-replicate from other brokersConsumer-side CRC check

PostgreSQL's chapter is precise about scope: "Only data pages are protected by checksums; internal data structures and temporary files are not," and the initdb reference adds that failures "will be reported in the pg_stat_database view." The btrfs docs describe the trade-off for its default: CRC32C is "not collision-resistant but still good error detection capabilities."

Fix: turn on checksums everywhere they exist, monitor the counters (checksum_failures, zpool status, btrfs device stats), scrub on a schedule, and keep a CRC-32C or SHA-256 per object in your own blob store so you can scrub it yourself.

Mechanics ​

CRC by hand, then by the CPU Good to know ​

The diagram above divides 11010011101100 by 1011. Real CRC-32 adds four conventions: a 33-bit generator, bits processed least-significant first (the reflected form, which is why Go's constants are 0xedb88320 and 0x82f63b78), an initial register of 0xFFFFFFFF (so leading zero bytes still change the result), and a final XOR with 0xFFFFFFFF. The program below implements that loop and checks it against the standard check value for the input 123456789.

go
// Command crcbyhand computes CRC-32 (IEEE) and CRC-32C (Castagnoli) bit by bit,
// the way the polynomial long division is described on paper, and compares the
// result with the table-driven / hardware-accelerated hash/crc32 package.
package main

import (
	"fmt"
	"hash/crc32"
)

// crcBitwise is the reflected (LSB-first) CRC used by Ethernet, gzip, PNG
// (poly 0xEDB88320) and by iSCSI, ext4, Kafka (poly 0x82F63B78).
// Each input bit "subtracts" (XORs) the generator polynomial when the
// low bit of the running remainder is 1: polynomial division over GF(2).
func crcBitwise(poly uint32, data []byte) uint32 {
	crc := ^uint32(0) // init 0xFFFFFFFF so leading zero bytes still change the result
	for _, b := range data {
		crc ^= uint32(b)
		for i := 0; i < 8; i++ {
			if crc&1 == 1 {
				crc = (crc >> 1) ^ poly
			} else {
				crc >>= 1
			}
		}
	}
	return ^crc // final XOR 0xFFFFFFFF
}

func main() {
	check := []byte("123456789") // the standard "check" input from the CRC catalogue
	castagnoli := crc32.MakeTable(crc32.Castagnoli)

	fmt.Printf("CRC-32  bitwise %08x  stdlib %08x\n",
		crcBitwise(crc32.IEEE, check), crc32.ChecksumIEEE(check))
	fmt.Printf("CRC-32C bitwise %08x  stdlib %08x\n",
		crcBitwise(crc32.Castagnoli, check), crc32.Checksum(check, castagnoli))

	// CRC is linear: crc(a) XOR crc(b) XOR crc(zeros) == crc(a XOR b) for equal lengths.
	// That is why it detects accidents well and forgery not at all.
	a, b := []byte("pay alice 10"), []byte("pay mallo 99")
	x := make([]byte, len(a))
	for i := range a {
		x[i] = a[i] ^ b[i]
	}
	zero := make([]byte, len(a))
	lhs := crc32.ChecksumIEEE(a) ^ crc32.ChecksumIEEE(b) ^ crc32.ChecksumIEEE(zero)
	fmt.Printf("linearity holds: %v\n", lhs == crc32.ChecksumIEEE(x))
}
text
$ go run ./crcbyhand
CRC-32  bitwise cbf43926  stdlib cbf43926
CRC-32C bitwise e3069283  stdlib e3069283
linearity holds: true

The last line is why CRC is not a MAC: crc(a) ⊕ crc(b) ⊕ crc(0…0) = crc(a ⊕ b). An attacker who flips chosen bits in the data can compute exactly which bits to flip in the CRC. Table-driven implementations (Go's MakeTable) process a byte per lookup instead of a bit per step; hardware does 8 bytes per instruction (CRC32CX on arm64, SSE4.2 CRC32 on amd64, plus carry-less multiply folding on newer x86); and the same linearity lets CRCs of concatenated blocks be combined without re-reading data, which is how S3 can offer full-object CRC checksums for multipart uploads.

Output sizes, encodings, truncation Must-know ​

A digest is bytes. How you print it changes its length, not its strength. Encodings are covered in Binary-to-Text Encoding.

AlgorithmBytesHex charsBase64 chars (padded)Example consumer
CRC-32 / CRC-32C488S3 x-amz-checksum-crc32c: base64
CRC-64/NVME, XXH3-6481612S3 x-amz-checksum-crc64nvme
MD5, XXH128163224Content-MD5 (base64), Laravel ETag (hex)
SHA-1204028git object ids (hex)
SHA-256, BLAKE3326444OCI digests (hex), S3 (base64)
SHA-384489664SRI integrity="sha384-…" (base64)
SHA-5126412888SRI sha512-…, release checksum files

Truncation. Cutting a cryptographic hash to t bits leaves a function with t-bit security for preimages and t/2 for collisions. git abbreviates ids for humans (git log --oneline) but stores and compares full ids; the same goes for the short image ids Docker prints. Truncating SHA-256 to 128 bits for a cache key is fine (2^64 collision work); to 32 bits it is a CRC with no guarantees. Never compare truncated digests for security decisions.

Byte order and case. Hex should be lowercase for comparison (hash_equals is case-sensitive). CRC-32 stored as an integer has an endianness: gzip stores it little-endian (see the byte-level dump), S3 sends it as base64 of the big-endian bytes, PHP's crc32() returns an int that you format with %08x.

Birthday bound: how many items before a collision Must-know ​

With k random n-bit values, the chance that some pair collides is approximately p ≈ 1 − exp(−k² / 2^(n+1)), so collisions become likely around k ≈ 2^(n/2). This is why a 32-bit CRC is useless as an identifier: 77 000 items give a 50 % chance of a duplicate.

go
// Command birthday prints the birthday bound: how many random n-bit hashes you
// can draw before the chance of any collision reaches p, and the collision
// probability for a given count. p ≈ 1 - exp(-k²/2^(n+1)).
package main

import (
	"fmt"
	"math"
)

func itemsFor(bits int, p float64) float64 {
	return math.Sqrt(2 * math.Pow(2, float64(bits)) * math.Log(1/(1-p)))
}

func probFor(bits int, k float64) float64 {
	return -math.Expm1(-k * k / math.Pow(2, float64(bits+1)))
}

func main() {
	fmt.Printf("%-6s %-16s %-16s %-14s\n", "bits", "items for 1e-9", "items for 50%", "P(coll) @1e9")
	for _, b := range []int{32, 64, 128, 160, 256} {
		fmt.Printf("%-6d %-16.3g %-16.3g %-14.3g\n", b, itemsFor(b, 1e-9), itemsFor(b, 0.5), probFor(b, 1e9))
	}
}
text
$ go run ./birthday
bits   items for 1e-9   items for 50%    P(coll) @1e9
32     2.93             7.72e+04         1
64     1.92e+05         5.06e+09         0.0267
128    8.25e+14         2.17e+19         1.47e-21
160    5.41e+19         1.42e+24         3.42e-31
256    1.52e+34         4.01e+38         4.32e-60

Read it as a design table. A 64-bit hash over one billion objects has a 2.7 % chance of some collision; fine for a cache key or a dedup pre-check, not for a primary key. 128 bits gives one-in-10^21 at a billion items; fine for random data, but not against an attacker who can construct collisions in a non-cryptographic 128-bit function. 256 bits is the standard for content addressing.

Performance you measure Important ​

go
// Command bench measures single-core throughput (MB/s) of common checksums and
// hashes on one in-memory buffer. Numbers are machine-specific; run it yourself.
package main

import (
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha3"
	"crypto/sha512"
	"fmt"
	"hash"
	"hash/adler32"
	"hash/crc32"
	"hash/fnv"
	"runtime"
	"time"

	"github.com/cespare/xxhash/v2"
	"github.com/spaolacci/murmur3"
	"github.com/zeebo/blake3"
	"github.com/zeebo/xxh3"
	"golang.org/x/crypto/blake2b"
)

func main() {
	const size = 256 << 20 // 256 MiB
	buf := make([]byte, size)
	for i := range buf {
		buf[i] = byte(i*31 + i>>8)
	}
	b2, _ := blake2b.New256(nil)
	algos := []struct {
		name string
		h    hash.Hash
	}{
		{"crc32 (IEEE)", crc32.NewIEEE()},
		{"crc32c (Castagnoli)", crc32.New(crc32.MakeTable(crc32.Castagnoli))},
		{"adler32", adler32.New()},
		{"fnv-1a 64", fnv.New64a()},
		{"murmur3 128", murmur3.New128()},
		{"xxhash64", xxhash.New()},
		{"xxh3 64", xxh3.New()},
		{"md5", md5.New()},
		{"sha1", sha1.New()},
		{"sha256", sha256.New()},
		{"sha512", sha512.New()},
		{"sha3-256", sha3.New256()},
		{"blake2b-256", b2},
		{"blake3", blake3.New()},
	}
	fmt.Printf("%s/%s, %d MiB buffer, 1 goroutine\n", runtime.GOOS, runtime.GOARCH, size>>20)
	for _, a := range algos {
		start := time.Now()
		a.h.Write(buf)
		a.h.Sum(nil)
		el := time.Since(start)
		fmt.Printf("%-20s %8.0f MB/s\n", a.name, float64(size)/1e6/el.Seconds())
	}
}
text
$ go run ./bench            # Apple M5, macOS, Go 1.27, one goroutine, 256 MiB buffer
darwin/arm64, 256 MiB buffer, 1 goroutine
crc32 (IEEE)            10940 MB/s
crc32c (Castagnoli)     11886 MB/s
adler32                  4086 MB/s
fnv-1a 64                1108 MB/s
murmur3 128              9384 MB/s
xxhash64                26456 MB/s
xxh3 64                 36518 MB/s
md5                       921 MB/s
sha1                     3390 MB/s
sha256                   3368 MB/s
sha512                   1970 MB/s
sha3-256                 1111 MB/s
blake2b-256              1445 MB/s
blake3                   1023 MB/s
ResultWhy on this machineWhat changes elsewhere
CRC-32 ≈ CRC-32CARMv8 has instructions for both polynomialsGo's amd64 code uses the SSE 4.2 CRC32 instruction for Castagnoli and carry-less multiply (PCLMULQDQ) for IEEE
XXH3 fastest (36 GB/s)NEON vector path in zeebo/xxh3xxHash's own table: 59 GB/s with AVX2 on an i7-9700K
SHA-256 ≈ SHA-1 > MD5ARMv8 SHA-256 and SHA-1 instructions; MD5 has none and is serialWithout SHA instructions SHA-256 is far slower: btrfs measured it at 16–78× the cycles of CRC32C depending on the library
BLAKE3 slowestzeebo/blake3 ships SSE4.1/AVX2 assembly for amd64 only; arm64 runs pure GoThe C/Rust BLAKE3 with NEON or AVX-512 is many GB/s and scales with threads
FNV slow on big buffersByte-at-a-time multiply loopFine for 8-byte keys; per-call overhead dominates there

The rule: an algorithm's reputation is a property of an implementation on a CPU. The btrfs docs measured the same ordering on an Intel CPU (CRC32C 470 cycles/4 KiB, XXHASH 870, SHA256 7 600 to 37 000 depending on library). Measure with your language, your library and your hardware before choosing for speed.

Byte-level view: gzip trailer, git object, OCI layer Good to know ​

gzip trailer. The last 8 bytes of a gzip member are CRC-32 and ISIZE, both little-endian (RFC 1952: "This contains a Cyclic Redundancy Check value of the uncompressed data"). Here, the alpine arm64 layer:

text
$ xxd -s -8 layer.tar.gz
003e7197: ece9 90c3 00fa 8a00                      ........
          └─CRC32─┘ └─ISIZE─┘
CRC32 = 0xc390e9ec (bytes ec e9 90 c3 reversed)   ISIZE = 0x008afa00 = 9107968
$ gunzip -c layer.tar.gz > layer.tar && crc32 layer.tar
c390e9ec

git loose object. zlib("blob 6\0hello\n"), whose zlib stream itself ends with an Adler-32:

text
$ printf 'hello\n' > hello.txt && git hash-object -w hello.txt
ce013625030ba8dba906f756967f9e9ca394464a
$ xxd .git/objects/ce/013625030ba8dba906f756967f9e9ca394464a
00000000: 7801 4bca c94f 5230 63c8 48cd c9c9 e702  x.K..OR0c.H.....
00000010: 001d c504 14                             .....
          78 01 = zlib header           1d c5 04 14 = Adler-32 of "blob 6\0hello\n"
$ printf 'blob 6\0hello\n' | shasum -a 1
ce013625030ba8dba906f756967f9e9ca394464a  -

OCI layer digest vs diff_id. The registry addresses the compressed bytes; the image config lists the hash of the uncompressed tar, so the same layer recompressed differently gets a new digest but the same diff_id.

text
layer.tar.gz  sha256:3f26bc2dec0b515f1c2818f6e13a8f1da1f88179a008445d4e587233386bff78  (4092319 bytes)
layer.tar     sha256:88b4fba61c4c714a2fc173ddf7e9324a257304696830bf41ad28ecc58c11c95f  = config.rootfs.diff_ids[0]

Knobs and error messages Must-know ​

ProductKnobError / signal you will see
PostgreSQLinitdb --data-checksums (default) / --no-data-checksums; pg_checksums --enable/--check; SHOW data_checksums; ignore_checksum_failureWARNING: page verification failed, calculated checksum N but expected M, then ERROR: invalid page in block …; pg_stat_database.checksum_failures
MySQL InnoDBinnodb_checksum_algorithm (crc32, strict_crc32)Page corruption in error log; innochecksum
Kafkaconsumer check.crcs (default true)CorruptRecordException: "This message has failed its CRC checksum, exceeds the valid size, has a null key for a compacted topic, or is otherwise corrupt."
Amazon S3x-amz-checksum-<algo> headers; full-object vs composite checksum types; trailing checksums for chunked uploadsBadDigest
Docker / containerdPull by @sha256:filesystem layer verification failed for digest sha256:…; manifest verification failed for digest …
gitgit fsck, --object-format=sha256error: inflate: data stream error (incorrect data check) (zlib Adler-32 failed); error: <id>: hash-path mismatch, found at: .git/objects/… (see Lab)
ZFSchecksum=on/fletcher4/sha256/blake3 per datasetzpool status CKSUM column
btrfschecksum chosen at mkfs.btrfs time: crc32c, xxhash, sha256, blake2checksum errors in the kernel log and btrfs device stats
gzipnonegzip: invalid compressed data--crc error (reproduced in the Lab)
Laravelcache.headers:…;etag; Storage::checksum($path, ['checksum_algo' => 'sha256'])UnableToProvideChecksum when the adapter cannot

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Upload arrives corruptedEnd-to-end SHA-256 (or CRC-32C) from clientClient sends digest header; server hashes while streamingCatches every hop, including your own bugsClient must compute it; one extra pass if not streamed
Same file stored 4 000 timesContent address + unique indexsha256 column, UNIQUE, createOrFirstStorage and upload work drop to one copyMust handle delete with reference counts
Downloaded artefact tampered or truncatedVerify published SHA-256 before usesha256sum -c, hash_file, Go io.Copy into sha256Simple; detects mirrors and truncationDigest must come from a trusted channel
Webhook forgedHMAC-SHA256 over raw body + timestamphash_hmac + hash_equals, crypto/hmacAuthenticity and integritySecret rotation, clock skew
Clients re-download unchanged JSONStrong ETag + 304xxh128 of body, If-None-MatchBandwidth and latency savedServer still renders the body to hash it
Route keys to shardsFixed portable hashXXH3 / Murmur3 modulo or ringSame answer in Go, PHP, SQLModulo reshuffles on resize: use consistent hashing
Stored blobs silently rotScrub job with stored CRC-32C/SHA-256Periodic re-read and compareYou find rot before users doRead I/O cost; needs a second copy to repair

Verify an upload end to end ​

Go: one pass, three destinations. io.TeeReader copies every byte it reads into the hash writers while io.Copy writes the file; nothing is buffered whole in memory, and the file only gets its final name after the digest matches.

go
// Command stream hashes an upload while writing it to disk, in one pass:
// the body is read once, written to a temp file and fed to SHA-256 and CRC-32C
// at the same time. The file is only moved into place if the digest matches
// what the client claimed (here: a hex SHA-256 in X-Content-SHA256).
package main

import (
	"crypto/sha256"
	"crypto/subtle"
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"hash/crc32"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
)

const storeDir = "./blobs"

func upload(w http.ResponseWriter, r *http.Request) {
	want, err := hex.DecodeString(r.Header.Get("X-Content-SHA256"))
	if err != nil || len(want) != sha256.Size {
		http.Error(w, "missing or malformed X-Content-SHA256", http.StatusBadRequest)
		return
	}
	tmp, err := os.CreateTemp(storeDir, "upload-*")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer os.Remove(tmp.Name()) // no-op after a successful rename

	sha := sha256.New()
	crc := crc32.New(crc32.MakeTable(crc32.Castagnoli))
	// TeeReader: every byte read from the body is also written to both hashes.
	body := io.TeeReader(http.MaxBytesReader(w, r.Body, 1<<30), io.MultiWriter(sha, crc))
	n, err := io.Copy(tmp, body)
	if cerr := tmp.Close(); err == nil {
		err = cerr
	}
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	got := sha.Sum(nil)
	if subtle.ConstantTimeCompare(got, want) != 1 {
		http.Error(w, "BadDigest: body does not match X-Content-SHA256", http.StatusUnprocessableEntity)
		return
	}
	// Content addressing: the name IS the digest, so a duplicate upload lands on the same path.
	final := filepath.Join(storeDir, hex.EncodeToString(got))
	if err := os.Rename(tmp.Name(), final); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("ETag", `"`+hex.EncodeToString(got)+`"`)
	w.Header().Set("X-Checksum-CRC32C", base64.StdEncoding.EncodeToString(crc.Sum(nil)))
	fmt.Fprintf(w, "stored %d bytes as sha256:%x\n", n, got)
}

func main() {
	if err := os.MkdirAll(storeDir, 0o755); err != nil {
		log.Fatal(err)
	}
	http.HandleFunc("PUT /blobs", upload)
	log.Println("listening on :8090")
	log.Fatal(http.ListenAndServe(":8090", nil))
}

Laravel: the same two digests in one read loop, then a constant-time compare, then storage under the content address.

php
<?php

namespace App\Http\Controllers;

use App\Models\Blob;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

/**
 * Upload once, hash while reading, store by content address, dedupe with a unique index.
 * The client sends the expected SHA-256 (hex) in X-Content-SHA256, like S3's x-amz-checksum-*.
 */
class StreamHashUpload
{
    public function __invoke(Request $request): JsonResponse
    {
        $request->validate(['file' => ['required', 'file', 'max:1048576']]); // KiB -> 1 GiB
        $expected = strtolower((string) $request->header('X-Content-SHA256'));
        abort_unless(preg_match('/^[0-9a-f]{64}$/', $expected) === 1, 400, 'X-Content-SHA256 required');

        $file = $request->file('file');
        $in = fopen($file->getRealPath(), 'rb');

        // One pass over the bytes feeds two digests: SHA-256 (identity) and CRC-32C (cheap scrub).
        $sha = hash_init('sha256');
        $crc = hash_init('crc32c');
        while (! feof($in)) {
            $chunk = fread($in, 1 << 20);
            if ($chunk === false) {
                abort(500, 'read error');
            }
            hash_update($sha, $chunk);
            hash_update($crc, $chunk);
        }
        $digest = hash_final($sha);
        $crc32c = hash_final($crc);

        // hash_equals: constant-time, and both sides are lowercase hex of equal length.
        abort_unless(hash_equals($expected, $digest), 422, 'BadDigest: body does not match X-Content-SHA256');

        $path = 'blobs/'.substr($digest, 0, 2).'/'.$digest; // fan-out like .git/objects/ab/cdef...
        rewind($in);
        if (! Storage::disk('s3')->exists($path)) {
            Storage::disk('s3')->writeStream($path, $in);
        }
        fclose($in);

        // createOrFirst relies on the unique index: two concurrent uploads of the same bytes
        // both end up pointing at one row instead of racing a SELECT-then-INSERT.
        $blob = Blob::query()->createOrFirst(
            ['sha256' => $digest],
            ['size' => $file->getSize(), 'crc32c' => $crc32c, 'mime' => $file->getMimeType(), 'disk' => 's3', 'path' => $path],
        );

        return response()->json([
            'id' => $blob->id,
            'digest' => 'sha256:'.$digest,
            'deduplicated' => ! $blob->wasRecentlyCreated,
        ], $blob->wasRecentlyCreated ? 201 : 200)->setEtag($digest);
    }
}

With S3 as the final store, also send x-amz-checksum-sha256 (base64 of the raw 32 bytes, not hex) so S3 re-verifies on its side; the AWS SDKs add x-amz-checksum-crc64nvme automatically.

Deduplicate stored files ​

The database enforces "one copy per content" with a unique index; the application never needs a racy "does it exist?" query.

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('blobs', function (Blueprint $table) {
            $table->id();
            // Lowercase hex: portable across drivers. binary('sha256', length: 32, fixed: true)
            // halves the size on MySQL, but raw bytes need care when bound on PostgreSQL (bytea).
            $table->char('sha256', 64)->unique(); // the content address
            $table->unsignedBigInteger('size');
            $table->string('crc32c', 8);   // cheap re-check for scrubbing jobs
            $table->string('mime')->nullable();
            $table->string('disk');
            $table->string('path');
            $table->timestamps();
        });

        Schema::create('attachments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('blob_id')->constrained('blobs'); // many rows, one stored copy
            $table->morphs('attachable');
            $table->string('original_name');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('attachments');
        Schema::dropIfExists('blobs');
    }
};
sql
-- Not executed here (no database running); syntax and example values from the PostgreSQL 19 docs.
-- PostgreSQL 18 added crc32()/crc32c(); sha256() is older. crc32c('abc'::bytea) -> 910901175
CREATE TABLE blobs (
  id         bigserial PRIMARY KEY,
  sha256     char(64)  NOT NULL UNIQUE,        -- content address, lowercase hex
  size       bigint    NOT NULL,
  crc32c     char(8)   NOT NULL,               -- cheap scrub check
  path       text      NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

-- Insert-or-get in one statement; concurrent uploads of the same bytes cannot both insert.
INSERT INTO blobs (sha256, size, crc32c, path)
VALUES (encode(sha256('hello'::bytea), 'hex'), 5, lpad(to_hex(crc32c('hello'::bytea)), 8, '0'), 'blobs/2c/2cf24d…')
ON CONFLICT (sha256) DO UPDATE SET sha256 = EXCLUDED.sha256
RETURNING id, (xmax = 0) AS inserted;

-- Is this cluster protected against page-level bit rot?
SHOW data_checksums;                                     -- on
SELECT datname, checksum_failures, checksum_last_failure
FROM pg_stat_database WHERE checksum_failures > 0;

Blob::createOrFirst() in Laravel 13 is the Eloquent form of the same idea: it tries the insert inside a savepoint and, on UniqueConstraintViolationException, reads the existing row.

Verify a download ​

php
<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use RuntimeException;

/**
 * Download a release artifact to disk without loading it in memory, then verify the
 * published SHA-256 before anything uses it (the "sha256sum -c" step, in Laravel).
 */
final class VerifyDownload
{
    public function fetch(string $url, string $expectedSha256, string $target): string
    {
        $tmp = $target.'.part';

        Http::timeout(120)
            ->retry(3, 500)
            ->sink($tmp)            // Guzzle streams the body straight into the file
            ->get($url)
            ->throw();

        $actual = hash_file('sha256', $tmp); // streams the file in blocks

        if (! hash_equals(strtolower($expectedSha256), $actual)) {
            @unlink($tmp);
            throw new RuntimeException("checksum mismatch for {$url}: expected {$expectedSha256}, got {$actual}");
        }

        rename($tmp, $target); // only verified bytes ever reach the final name

        return $actual;
    }

    /** Verify a file already in storage with the driver's checksum (Flysystem 3.7+). */
    public function verifyStored(string $disk, string $path, string $expectedSha256): bool
    {
        // On S3 the default checksum is the ETag, which is NOT a SHA-256 (and not even MD5
        // for multipart uploads), so ask for the algorithm explicitly. S3 cannot compute sha256
        // on demand, so Flysystem falls back to streaming the whole object through PHP.
        $actual = Storage::disk($disk)
            ->checksum($path, ['checksum_algo' => 'sha256']);

        return is_string($actual) && hash_equals(strtolower($expectedSha256), $actual);
    }
}

The shell equivalent is shasum -a 256 -c SHA256SUMS (Linux: sha256sum -c). The digest file must come from somewhere the attacker cannot also write: a signed release, a different domain, your lockfile in git. Flysystem's docs warn about the other trap in this file: on S3 "In some cases, an Etag pseudo-checksum is provided", so request checksum_algo explicitly.

Authenticate a webhook ​

go
// Command hmacverify shows why a plain hash is not authentication:
// anyone can recompute sha256(body), only the key holder can compute the HMAC.
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
)

func sign(key, msg []byte) string {
	m := hmac.New(sha256.New, key)
	m.Write(msg)
	return hex.EncodeToString(m.Sum(nil))
}

// verify compares in constant time; == on strings leaks how many leading bytes matched.
func verify(key, msg []byte, sigHex string) bool {
	sig, err := hex.DecodeString(sigHex)
	if err != nil {
		return false
	}
	m := hmac.New(sha256.New, key)
	m.Write(msg)
	return hmac.Equal(m.Sum(nil), sig)
}

func main() {
	key := []byte("whsec_test_only_not_a_real_secret")
	body := []byte(`{"event":"payment.succeeded","amount":1000}`)

	plain := sha256.Sum256(body)
	fmt.Println("sha256(body)      :", hex.EncodeToString(plain[:]), "<- attacker can compute this too")
	sig := sign(key, body)
	fmt.Println("hmac-sha256(body) :", sig)

	tampered := []byte(`{"event":"payment.succeeded","amount":9999}`)
	fmt.Println("valid original    :", verify(key, body, sig))
	fmt.Println("valid tampered    :", verify(key, tampered, sig))
}
text
$ go run ./hmacverify
sha256(body)      : c65f7ef3454ae471e5342a3a1088d3807ec18512ac2564c1b38f00eab21e4244 <- attacker can compute this too
hmac-sha256(body) : 7c164a70f8248426be2756b8c9665472c55c21ab9232b0dc9f08d982ffa80152
valid original    : true
valid tampered    : false
php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Integrity + authenticity for an incoming webhook: HMAC-SHA256 over timestamp and raw body.
 * A plain sha256(body) header would prove nothing; anyone can compute it.
 * Full treatment of signing schemes: /foundations/password-hashing-signed-tokens.
 */
class VerifyWebhookSignature
{
    public function handle(Request $request, Closure $next): Response
    {
        $secret = (string) config('services.billing.webhook_secret');
        $timestamp = (string) $request->header('X-Timestamp');
        $signature = (string) $request->header('X-Signature'); // hex HMAC

        abort_if($secret === '' || $timestamp === '' || $signature === '', 401);
        abort_if(abs(time() - (int) $timestamp) > 300, 401, 'stale signature'); // replay window

        // Sign the RAW body: re-encoding JSON changes bytes and breaks the MAC.
        $expected = hash_hmac('sha256', $timestamp.'.'.$request->getContent(), $secret);

        abort_unless(hash_equals($expected, strtolower($signature)), 401, 'bad signature');

        return $next($request);
    }
}

ETag and 304 ​

go
// Command etag serves a resource with a strong ETag derived from its bytes and
// answers If-None-Match with 304 Not Modified, so unchanged content is not resent.
package main

import (
	"encoding/base64"
	"log"
	"net/http"
	"strings"

	"github.com/zeebo/xxh3"
)

var body = []byte(`{"plan":"pro","price":20}`)

// etagFor uses a fast 128-bit non-cryptographic hash: an ETag only has to change
// when the bytes change; nobody gains anything by forging one for their own cache.
func etagFor(b []byte) string {
	sum := xxh3.Hash128(b).Bytes()
	return `"` + base64.RawURLEncoding.EncodeToString(sum[:]) + `"`
}

func matches(ifNoneMatch, etag string) bool {
	for _, candidate := range strings.Split(ifNoneMatch, ",") {
		c := strings.TrimSpace(candidate)
		if c == "*" || strings.TrimPrefix(c, "W/") == etag { // weak comparison for GET
			return true
		}
	}
	return false
}

func handler(w http.ResponseWriter, r *http.Request) {
	tag := etagFor(body)
	w.Header().Set("ETag", tag)
	w.Header().Set("Cache-Control", "no-cache") // always revalidate, reuse when 304
	if inm := r.Header.Get("If-None-Match"); inm != "" && matches(inm, tag) {
		w.WriteHeader(http.StatusNotModified)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.Write(body)
}

func main() {
	http.HandleFunc("GET /plan", handler)
	log.Fatal(http.ListenAndServe(":8081", nil))
}

In Laravel this is one middleware string; the framework source computes hash('xxh128', $response->getContent()) and calls isNotModified($request):

php
<?php

use App\Http\Controllers\StreamHashUpload;
use App\Http\Middleware\VerifyWebhookSignature;
use Illuminate\Support\Facades\Route;

// Built-in ETag: Laravel's SetCacheHeaders middleware hashes the response body with xxh128
// and answers If-None-Match with 304 Not Modified.
Route::middleware('cache.headers:public;max_age=60;etag')->group(function () {
    Route::get('/plans', fn () => ['plan' => 'pro', 'price' => 20]);
});

// POST multipart: PHP only parses uploaded files ($request->file()) for POST requests.
Route::post('/blobs', StreamHashUpload::class);

Route::post('/webhooks/billing', fn () => response()->noContent())
    ->middleware(VerifyWebhookSignature::class);

Stable sharding and bucketing ​

go
// Command shard contrasts two jobs for a non-cryptographic hash:
// a per-process random seed for in-memory tables (hash/maphash, flood resistant)
// and a fixed, portable hash for routing keys to shards (xxh3), which must give
// the same answer in every process, language and deploy.
package main

import (
	"fmt"
	"hash/maphash"

	"github.com/zeebo/xxh3"
)

func shardFor(key string, shards uint64) uint64 {
	// Stable across machines and restarts. Plain modulo reshuffles most keys when
	// `shards` changes; see consistent hashing for the fix.
	// The 60-bit mask matches the PHP version, whose ints are signed 64-bit.
	return (xxh3.HashString(key) & (1<<60 - 1)) % shards
}

func main() {
	seed := maphash.MakeSeed() // random per process: different output every run
	for _, k := range []string{"user:42", "user:43", "order:9001"} {
		fmt.Printf("%-11s maphash=%016x  shard(of 8)=%d\n", k, maphash.String(seed, k), shardFor(k, 8))
	}
}
text
$ go run ./shard        # maphash column differs on every run; shard column never does
user:42     maphash=680a1e3fc77cedb4  shard(of 8)=2
user:43     maphash=d7b95e3f57d1ca77  shard(of 8)=5
order:9001  maphash=26c59a0332f003d7  shard(of 8)=2

The PHP class below computes the same shard numbers (same XXH3, same 60-bit mask) and shows every algorithm from this page through hash():

php
<?php

namespace App\Support;

/**
 * The same operations as the Go snippets, with PHP's ext/hash (always enabled).
 * Expected outputs are copied from the Go runs on the same inputs.
 */
final class Checksums
{
    public static function demo(): array
    {
        $check = '123456789';

        return [
            // crc32() returns an int; format it as 8 hex digits. Same as hash('crc32b').
            'crc32_int' => sprintf('%08x', crc32($check)),      // cbf43926
            'crc32b' => hash('crc32b', $check),                 // cbf43926 (zip/gzip/PNG CRC-32)
            'crc32_bzip2' => hash('crc32', $check),             // 181989fc: a different CRC (BZIP2/AAL5), not zip's
            'crc32c' => hash('crc32c', $check),                 // e3069283 (Castagnoli, iSCSI, Kafka)
            'adler32' => hash('adler32', $check),
            'fnv1a64' => hash('fnv1a64', $check),
            'murmur3f' => hash('murmur3f', $check),             // MurmurHash3 x64 128-bit
            'xxh3' => hash('xxh3', $check),                     // 64-bit, PHP >= 8.1
            'xxh128' => hash('xxh128', $check),
            'md5' => hash('md5', $check),
            'sha256_hex' => hash('sha256', $check),             // 64 hex chars
            'sha256_b64' => base64_encode(hash('sha256', $check, true)), // 44 chars, S3/SRI style
            'sha3_256' => hash('sha3-256', $check),
            'blake2b' => bin2hex(sodium_crypto_generichash($check)), // BLAKE2b-256 via ext/sodium
        ];
    }

    /** Git blob id: sha1("blob <len>\0" . content). */
    public static function gitBlobId(string $content): string
    {
        return sha1('blob '.strlen($content)."\0".$content); // "what is up, doc?" -> bd9dbf5a...
    }

    /** OCI/Docker digest string for a file; hash_file() reads it incrementally, not into memory. */
    public static function ociDigest(string $path): string
    {
        return 'sha256:'.hash_file('sha256', $path);
    }

    /** Incremental hashing of any stream (socket, php://input, S3 read stream). */
    public static function streamDigest($stream, string $algo = 'sha256'): string
    {
        $ctx = hash_init($algo);
        while (! feof($stream)) {
            hash_update_stream($ctx, $stream, 1 << 20); // up to 1 MiB per call
        }

        return hash_final($ctx);
    }

    /** Stable shard number: xxh3 is portable across languages, unlike PHP's internal array hash. */
    public static function shardFor(string $key, int $shards): int
    {
        // Low 60 bits (15 hex digits) fit a positive PHP int; Go uses the same mask.
        return hexdec(substr(hash('xxh3', $key), 1)) % $shards;
    }
}

Scrub your own blob store ​

A nightly job walks the blobs table in keyset order (Pagination), streams each object, recomputes CRC-32C (fast) and, on a sampled fraction, SHA-256 (the address), and records mismatches. On a mismatch it restores from a second copy (another bucket, another region) and alerts. This is the application-level version of zpool scrub.

text
1  job      : SELECT id, path, crc32c FROM blobs WHERE id > :last ORDER BY id LIMIT 1000
2  job      : for each: stream object -> crc32c; 1 % sample also -> sha256
3  job      : mismatch -> copy from replica bucket, verify sha256 == row.sha256, overwrite
4  job      : metrics: scrub_bytes_total, scrub_mismatch_total; alert on mismatch > 0

Choosing ​

SituationChooseOutputReason
New on-disk or wire format, detect corruptionCRC-32C32 bits per block ≤ 64 KiBHardware speed, HD=4 or better at those lengths
Very large objects (multi-GB)CRC-64/NVME or SHA-25664 / 256 bits32 bits is thin over huge spans; S3's default is CRC-64/NVME
Existing format (gzip, zip, PNG, Ethernet)CRC-32 (IEEE)32 bitsCompatibility
Hash table, Bloom filter, in-memory indexRuntime map hash / XXH3 / Murmur364 bitsSpeed; seeded if keys come from users
Shard routing across services and languagesXXH3 or Murmur3 with a fixed seed64 bitsStable and portable
Cache key, ETagXXH128 (or SHA-256 if keys are user-controlled and shared)128 bitsLaravel default; collisions cost only a stale cache unless users choose input
Dedup of user uploads, content-addressed storageSHA-256256 bitsUsers can craft collisions for anything weaker
Downloads, container images, SBOMs, SRISHA-256 (SRI often SHA-384)256/384Ecosystem standard
Hashing big local files fast, x86 with SIMDBLAKE3256 bitsParallel tree hashing
Webhooks, signed URLs, cookiesHMAC-SHA256256 bitsNeeds a key
PasswordsArgon2id / bcrypt, never a plain hash—See Password Hashing
FIPS environmentSHA-256/384/512, SHA-3—Only the FIPS 180-4 and FIPS 202 families are in those standards; BLAKE and xxHash are not

In architecture: from a single process to a distributed system ​

Hashing changes role as a system grows: inside one process it is a data-structure detail; across services it becomes a contract that every language must reproduce bit for bit; across regions it is how you know two copies are the same.

Monolith: one process, one database ​

Everyday example: a Laravel app stores user avatars. The upload controller hashes the file while saving it, rejects mismatches with 422, and stores sha256 in a uniquely indexed column; avatars become avatars/ab/abcdef….png, served with Cache-Control: immutable because the URL changes when the content does. JSON endpoints use cache.headers:…;etag. PostgreSQL has data_checksums = on. Nothing else is needed: one process, one place that hashes, one database enforcing uniqueness.

Modular monolith and multiple databases ​

Once modules own their tables, the content hash becomes a shared identifier: the Media module exposes sha256:<hex> digests, and Billing stores invoice PDFs by digest without knowing paths. The rule to write down: which function, which encoding (lowercase hex vs base64), which bytes (before or after image resizing, before or after compression). Two modules hashing "the same file" before and after EXIF stripping will never agree.

Microservices ​

Production example: a document service (Go) receives uploads, an indexing service (PHP) and a thumbnailer (Go) consume document.stored events from Kafka.

text
1  client       -> PUT /documents  X-Content-SHA256: ed4769b6…   (TLS to the gateway)
2  doc-service  : TeeReader -> S3 PutObject with x-amz-checksum-sha256 (base64), BadDigest -> 422
3  doc-service  : INSERT blobs ... ON CONFLICT (sha256) ; outbox row {digest, size}
4  relay        -> Kafka document.stored {digest:"sha256:ed47…", size:1048576}  (batch CRC-32C)
5  indexer      : GetObject; recompute sha256 while streaming; mismatch -> DLQ, alert
6  thumbnailer  : cache key = sha256 of source + "w=256" ; same input never processed twice

What survives the boundaries is the digest, not the transport checks: TLS ends at the gateway, Kafka's CRC protects the event but not the S3 object, and the S3 checksum protects storage but not the indexer's download buffer. Each consumer re-verifies the digest carried in the event. Webhooks to partners are HMAC-signed; internal calls use mTLS (see system design) rather than per-message HMACs. Sharding of the indexer's work uses XXH3 of the document id, identical in Go and PHP (shardFor).

Distributed data: replicas, caches and multi-region ​

Replicas and caches raise the question "are these two copies equal?" without shipping both. Merkle trees answer it in O(log n) round trips: Cassandra's repair works "with merkle trees, which are a hierarchy of hashes", comparing tree hashes of token ranges and streaming only ranges that differ; ZFS send/receive streams carry Fletcher-4 checksums. Caches use content hashes as keys so invalidation is unnecessary: a new version has a new key. PostgreSQL makes checksums a cluster-wide property: pg_checksums must run on every node ("The same operation must be executed on every node in a replicated cluster"), and backups are checked with pg_verifybackup and tables with pg_amcheck, because a replica or backup is only useful if its own bytes are verified.

Scaling path ​

LoadWhat changes
1× (one server)SHA-256 on upload, ETags, Postgres checksums on. CPU cost invisible
10×Hashing becomes measurable on upload-heavy nodes: hash while streaming (never re-read), move ETag computation to cached content hashes instead of hashing every response, use XXH3 for internal cache keys
100×Offload: let clients send digests and S3 verify (x-amz-checksum-*); composite multipart checksums so parts are hashed in parallel; dedup pre-check by XXH3 in a Bloom filter before the SHA-256 lookup; scheduled scrubs with sampling; consistent hashing instead of modulo for shard routing; Merkle-based anti-entropy between regions

Troubleshooting ​

SymptomLikely causeCheck / fix
Go and PHP compute different CRC-32PHP hash('crc32') is the BZIP2 variantUse hash('crc32b') or crc32(); check value cbf43926 for 123456789
S3 returns BadDigestHeader digest in hex instead of base64, or body changed in a proxyx-amz-checksum-sha256 = base64 of 32 raw bytes; Content-MD5 = base64 of 16 raw bytes
S3 ETag does not equal md5sumMultipart upload or SSE-C/SSE-KMS encryptionCompare a full-object x-amz-checksum-* instead of the ETag
Same file, two different SHA-256Line-ending conversion (git autocrlf), BOM, re-encoded JSON, gzip timestamp in headerHash the exact bytes; compare with cmp -l
Docker filesystem layer verification failedCorrupt download, proxy cache, diskRemove the image, pull by digest again, check disk and proxy
docker pull image:tag gives a different image than yesterdayTag movedPin image@sha256:…
Postgres page verification failedStorage or memory corruptionCheck hardware, restore the relation from backup/replica; ignore_checksum_failure only to salvage
Webhook signature always failsFramework re-encoded the JSON body, or secret has whitespaceSign and verify $request->getContent() raw bytes; trim config
HMAC compare leaks timing== on stringshash_equals, hmac.Equal, subtle.ConstantTimeCompare
Hash-based shard map breaks after deployUsed a seeded hash (maphash, Python hash())Fixed algorithm and seed (XXH3, Murmur3)
ETag changes on every requestBody contains a timestamp or random order (map iteration)Make the representation deterministic; sort keys
ETags differ between serversETag from inode/mtime (Apache, nginx static)Content-derived ETag or same build artefacts
Upload digest check doubles latencyFile read twiceio.TeeReader / single read loop feeding the hash

Lab ​

All commands ran on macOS (Apple M5) with Go 1.27 from docs/snippets/foundations/checksums-hashing/go; outputs are pasted, except where noted.

1. Flip one bit and watch every checksum react.

go
// Command bitflip flips exactly one bit in a file-sized buffer and prints
// how every checksum and hash reacts. Usage: go run ./bitflip [file]
package main

import (
	"crypto/md5"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"hash/adler32"
	"hash/crc32"
	"hash/fnv"
	"math/bits"
	"os"

	"github.com/zeebo/blake3"
	"github.com/zeebo/xxh3"
)

type row struct {
	name string
	sum  func([]byte) []byte
}

func be32(v uint32) []byte { return []byte{byte(v >> 24), byte(v >> 16), byte(v >> 8), byte(v)} }
func be64(v uint64) []byte {
	return append(be32(uint32(v>>32)), be32(uint32(v))...)
}

// parity is the XOR of every bit: one bit of redundancy, catches any odd number of flips.
func parity(b []byte) []byte {
	var p byte
	for _, c := range b {
		p ^= c
	}
	return []byte{byte(bits.OnesCount8(p) & 1)}
}

func main() {
	data := []byte("The quick brown fox jumps over the lazy dog")
	if len(os.Args) > 1 {
		var err error
		if data, err = os.ReadFile(os.Args[1]); err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
	}
	castagnoli := crc32.MakeTable(crc32.Castagnoli)
	rows := []row{
		{"parity", parity},
		{"adler32", func(b []byte) []byte { return be32(adler32.Checksum(b)) }},
		{"crc32", func(b []byte) []byte { return be32(crc32.ChecksumIEEE(b)) }},
		{"crc32c", func(b []byte) []byte { return be32(crc32.Checksum(b, castagnoli)) }},
		{"fnv1a-64", func(b []byte) []byte { h := fnv.New64a(); h.Write(b); return h.Sum(nil) }},
		{"xxh3-64", func(b []byte) []byte { return be64(xxh3.Hash(b)) }},
		{"md5", func(b []byte) []byte { s := md5.Sum(b); return s[:] }},
		{"sha256", func(b []byte) []byte { s := sha256.Sum256(b); return s[:] }},
		{"blake3", func(b []byte) []byte { s := blake3.Sum256(b); return s[:] }},
	}

	flipped := append([]byte(nil), data...)
	flipped[len(flipped)/2] ^= 0x01 // one bit, in the middle

	fmt.Printf("%-9s %-18s %-18s %s\n", "algo", "original", "1 bit flipped", "bits changed")
	for _, r := range rows {
		a, b := r.sum(data), r.sum(flipped)
		diff := 0
		for i := range a {
			diff += bits.OnesCount8(a[i] ^ b[i])
		}
		fmt.Printf("%-9s %-18.16s %-18.16s %d/%d\n", r.name,
			hex.EncodeToString(a), hex.EncodeToString(b), diff, len(a)*8)
	}
}
text
$ go run ./bitflip
algo      original           1 bit flipped      bits changed
parity    01                 00                 1/8
adler32   5bdc0fda           5bc60fd9           5/32
crc32     414fa339           5667c7f9           11/32
crc32c    22620404           7e77eab0           17/32
fnv1a-64  f3f9b7f5e7e47110   37a8939b6298a471   29/64
xxh3-64   ce7d19a5418fb365   8ff8ef3dcba5dc2a   31/64
md5       9e107d9d372bb682   a04dc6c84d9bcb87   69/128
sha256    d7a8fbb307d78094   4df9e83ba4ace47c   123/256
blake3    2f1514181aadccd9   625a96fbb0c4a06b   129/256

All of them noticed. Adler-32 changed only 5 bits (the two sums move a little; no avalanche), the CRCs changed a handful (they are linear, not mixing), and the hashes flipped about half. With system tools on a 1 MiB random file:

text
$ head -c 1048576 /dev/urandom > f.bin && cp f.bin g.bin    # then flip bit 0 of byte 524288 in g.bin
$ cmp -l f.bin g.bin
524289  42  43
f.bin crc32=4621d954 cksum=833689930 md5=e5570d8657d6e907 sha256=ed4769b654dd3a19
g.bin crc32=2957ce7a cksum=1191072479 md5=c03e07377befce69 sha256=2a7da4aa3e589cff

2. Stream-hash a large upload. Start go run ./stream (listens on :8090), then:

text
$ SUM=$(shasum -a 256 f.bin | cut -d' ' -f1)
$ curl -s -X PUT -H "X-Content-SHA256: $SUM" --data-binary @f.bin localhost:8090/blobs
stored 1048576 bytes as sha256:ed4769b654dd3a19c0a8a9eb8e89565059df390952d41b0c701791983bda4f89
$ curl -si -X PUT -H "X-Content-SHA256: $SUM" --data-binary @g.bin localhost:8090/blobs   # 1 bit different
HTTP/1.1 422 Unprocessable Entity
BadDigest: body does not match X-Content-SHA256
$ ls blobs
ed4769b654dd3a19c0a8a9eb8e89565059df390952d41b0c701791983bda4f89

3. Compare MB/s on your machine. go run ./bench (output in Performance). Then openssl speed -evp sha256, and the b3sum CLI from the BLAKE3 repo on a 1 GB file (the README's own speed test) to compare an optimised multi-threaded BLAKE3 with our pure-Go arm64 number.

4. Verify a Docker image digest by hand (no Docker daemon needed). The registry API returns exactly the bytes the digest names.

text
$ TOKEN=$(curl -s "https://auth.docker.io/token?service=registry.docker.io&scope=repository:library/alpine:pull" \
    | python3 -c 'import sys,json; print(json.load(sys.stdin)["token"])')
$ curl -s -D hdr.txt -H "Authorization: Bearer $TOKEN" \
    -H 'Accept: application/vnd.oci.image.index.v1+json' \
    -o index.json https://registry-1.docker.io/v2/library/alpine/manifests/3.20
$ grep -i docker-content-digest hdr.txt ; shasum -a 256 index.json
docker-content-digest: sha256:d9e853e87e55526f6b2917df91a2115c36dd7c696a35be12163d44e6e2a4b6bc
d9e853e87e55526f6b2917df91a2115c36dd7c696a35be12163d44e6e2a4b6bc  index.json
$ # arm64 manifest -> layer blob, fetched by digest
$ curl -sL -H "Authorization: Bearer $TOKEN" -o layer.tar.gz \
    https://registry-1.docker.io/v2/library/alpine/blobs/sha256:3f26bc2dec0b515f1c2818f6e13a8f1da1f88179a008445d4e587233386bff78
$ shasum -a 256 layer.tar.gz
3f26bc2dec0b515f1c2818f6e13a8f1da1f88179a008445d4e587233386bff78  layer.tar.gz

The tag 3.20 resolved to that index on 2026-11-25; it will move. To pin it: docker pull alpine@sha256:d9e853e87e55526f6b2917df91a2115c36dd7c696a35be12163d44e6e2a4b6bc (not run here: the Docker daemon was stopped). Docker performs the same shasum comparison on every blob and fails with filesystem layer verification failed for digest when it does not match.

5. Verify a git object by hand.

text
$ echo -n "what is up, doc?" | git hash-object --stdin       # the Pro Git example
bd9dbf5aae1a3862dd1526723246b20206e5fc37
$ go run ./contentaddr
git blob  : bd9dbf5aae1a3862dd1526723246b20206e5fc37
oci digest: sha256:db725045c8aa08440db90673c6b692751460c3881414f69c9be1cfc52b55a1df (size 322)
merkle    : fc35373eb43210e3
after flip: 7f648b8daf782502 (only chunk 6 and its path to the root changed)
go
// Command contentaddr reproduces three content-addressing schemes by hand:
// a git blob id, an OCI/Docker digest, and a binary Merkle root over chunks.
package main

import (
	"crypto/sha1"
	"crypto/sha256"
	"fmt"
	"io"
	"os"
)

// gitBlobID is what `git hash-object` prints: SHA-1 over "blob <len>\x00" + content.
func gitBlobID(content []byte) string {
	h := sha1.New()
	fmt.Fprintf(h, "blob %d\x00", len(content))
	h.Write(content)
	return fmt.Sprintf("%x", h.Sum(nil))
}

// ociDigest is the "sha256:<hex>" string used by Docker/OCI for blobs and manifests.
func ociDigest(r io.Reader) (string, int64, error) {
	h := sha256.New()
	n, err := io.Copy(h, r)
	return fmt.Sprintf("sha256:%x", h.Sum(nil)), n, err
}

// merkleRoot hashes fixed-size chunks (leaves) and then pairs of hashes up to one root.
// Leaves and inner nodes get different prefixes (0x00 / 0x01) so an inner node can
// never be passed off as a leaf (the second-preimage trick RFC 6962 also prevents).
func merkleRoot(data []byte, chunk int) [32]byte {
	var level [][32]byte
	for off := 0; off < len(data) || off == 0; off += chunk {
		end := min(off+chunk, len(data))
		level = append(level, sha256.Sum256(append([]byte{0x00}, data[off:end]...)))
		if end == len(data) {
			break
		}
	}
	for len(level) > 1 {
		var next [][32]byte
		for i := 0; i < len(level); i += 2 {
			if i+1 == len(level) { // odd node is promoted unchanged
				next = append(next, level[i])
				continue
			}
			buf := append([]byte{0x01}, level[i][:]...)
			next = append(next, sha256.Sum256(append(buf, level[i+1][:]...)))
		}
		level = next
	}
	return level[0]
}

func main() {
	fmt.Println("git blob  :", gitBlobID([]byte("what is up, doc?")))

	f, err := os.Open("go.mod")
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer f.Close()
	d, n, err := ociDigest(f)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Printf("oci digest: %s (size %d)\n", d, n)

	data := make([]byte, 10_000)
	root := merkleRoot(data, 1024)
	data[7000] ^= 1 // corrupt one bit in chunk 6
	fmt.Printf("merkle    : %x\n", root[:8])
	r2 := merkleRoot(data, 1024)
	fmt.Printf("after flip: %x (only chunk 6 and its path to the root changed)\n", r2[:8])
}

The OCI digest of go.mod will differ on your copy (it hashes whatever bytes the file has); compare it with shasum -a 256 go.mod.

Now corrupt the repository from the byte-level section twice and let git fsck tell the two failures apart:

text
$ # flip one bit inside the zlib stream of .git/objects/ce/0136…
$ git fsck
error: inflate: data stream error (incorrect data check)          <- zlib's Adler-32 failed
error: unable to unpack header of .git/objects/ce/013625030ba8dba906f756967f9e9ca394464a
error: ce013625030ba8dba906f756967f9e9ca394464a: object corrupt or missing: .git/objects/ce/0136…
missing blob ce013625030ba8dba906f756967f9e9ca394464a
$ # replace the file with a VALID zlib stream of "blob 6\0hellO\n" under the old name
$ git fsck
error: 4b32b59cf6f008703c95a6d2284f027e6ef86b54: hash-path mismatch, found at: .git/objects/ce/0136…
missing blob ce013625030ba8dba906f756967f9e9ca394464a

The first is the checksum layer (accidental damage to the compressed bytes); the second is the content address layer (well-formed bytes that are not what the name promises). The same two layers in gzip:

text
$ printf 'hello world, this is gzip\n%.0s' {1..50} | gzip > t.gz    # then flip one bit of the CRC-32 trailer -> t2.gz
$ gzip -t t2.gz
gzip: invalid compressed data--crc error
gzip: t2.gz: uncompress failed

6. ETag round trip. go run ./etag, then curl -si localhost:8081/plan (200 with Etag: "QCBtYse8ERjY9cpmOLCKuQ") and curl -si -H 'If-None-Match: "QCBtYse8ERjY9cpmOLCKuQ"' localhost:8081/plan (HTTP/1.1 304 Not Modified, no body).

Common misconceptions ​

BeliefReality
"A hash makes data secure"A hash proves equality to a trusted digest. Authenticity needs a key (HMAC) or a signature
"CRC-32 is a weak hash"It is a strong error-detecting code with guaranteed burst detection; it is just not a hash against people
"All CRC-32s are equal"IEEE, Castagnoli, Koopman, BZIP2 variants give different values; PHP crc32 ≠ crc32b
"TCP/TLS protects my file end to end"Per hop or per session only; add an end-to-end digest
"MD5 is broken, so it detects nothing"It is broken for collisions chosen by attackers; it still detects accidental corruption
"64-bit xxHash is enough to identify files"2.7 % chance of some collision at 10^9 files, and anyone can craft collisions on purpose
"sha256(secret . data) is a MAC"Length extension forges it; use HMAC
"Go maps use SipHash"Go uses an AES-based or wyhash-style hash with a per-map random seed; Rust uses SipHash 1-3
"The S3 ETag is the MD5"Only for single-part, plain/SSE-S3 objects
"A Docker tag identifies an image"Tags move; digests do not
"BLAKE3 is always the fastest crypto hash"Depends on SIMD support in your implementation; on our arm64 Go build SHA-256 was 3× faster
"RAID protects against bit rot"Only filesystems with per-block checksums (ZFS, btrfs) know which copy is right
"Salting checksums makes them safer"Salts are for password hashing; checksums need no salt, MACs need a key
"Base64 digests are stronger than hex"Same bytes, different printing

Cheat sheet ​

TopicRemember
Three jobsAccidents → CRC-32C; buckets → XXH3/seeded hash; attackers → SHA-256; origin → HMAC
CRC check values123456789 → CRC-32 cbf43926, CRC-32C e3069283
Kafka, iSCSI, ext4, btrfsCRC-32C
Ethernet, gzip, zip, PNGCRC-32 (IEEE)
S3 default checksumCRC-64/NVME; send x-amz-checksum-* in base64
PostgreSQLdata_checksums on by default since 18; watch pg_stat_database.checksum_failures
Broken hashesMD5 and SHA-1: collisions practical; fine for non-adversarial fingerprints
Length extensionMD5/SHA-1/SHA-256/SHA-512 vulnerable; HMAC, SHA-3, BLAKE3, SHA-512/256 not
Birthday boundCollisions near 2^(n/2): 32 bits → 77k items, 64 bits → 5×10^9, 256 bits → never
Content addresssha256:<hex>; pin images by digest; dedup with a unique index
ETagLaravel cache.headers:…;etag = xxh128; 304 on If-None-Match
Compare digestsConstant time: hash_equals, hmac.Equal, subtle.ConstantTimeCompare
StreamingGo io.TeeReader / io.MultiWriter; PHP hash_init + hash_update_stream + hash_final
MeasureSpeed depends on CPU instructions: CRC32/CRC32C, SHA-NI/ARMv8 SHA, AVX2/NEON

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why can a CRC-32 not protect a webhook payload, even though it detects every 1-bit error? Must-know ​

Answer

Answer: CRC is linear and unkeyed: an attacker who changes the payload can recompute (or algebraically fix) the CRC. Detection of random errors says nothing about deliberate ones. Use HMAC-SHA256 with a shared secret. See CRC and HMAC.

2 — Kafka, iSCSI and ext4 chose CRC-32C over the Ethernet CRC-32. Give two reasons. Good to know ​

Answer

Answer: Better Hamming distance over the block sizes they use (RFC 3385: d=6 up to 5275 bits, d=4 up to 2^31−1), and a dedicated x86 SSE4.2 instruction for exactly that polynomial. See CRC-32 and CRC-32C.

3 — You store 10^9 objects keyed by a 64-bit XXH3. Roughly what is the chance of at least one collision, and what would you change? Important ​

Answer

Answer: About 2.7 % (birthday bound), before considering attackers. Use SHA-256 as the key, keeping XXH3 only as a fast pre-check. See Birthday bound.

4 — What is the difference between a collision attack and a second-preimage attack, and which one is practical against SHA-1? Important ​

Answer

Answer: Collision: attacker picks both inputs (~2^(n/2)). Second preimage: attacker must match a given input (~2^n). Collisions are practical against SHA-1 (SHAttered, 2017); second preimages are not. See Cryptographic properties.

5 — Why is sha256($secret . $query) an unsafe signature, and what are two safe alternatives? Must-know ​

Answer

Answer: SHA-256 outputs its full Merkle–Damgård state, so an attacker can extend the message and compute a valid tag (length extension). Use hash_hmac('sha256', …), or BLAKE3's keyed mode, which has no length extension. See SHA-2 and length extension.

6 — A user says the S3 ETag of their 2 GB upload does not equal md5sum. Is the file corrupt? Important ​

Answer

Answer: Probably not: multipart uploads (and SSE-KMS objects) have ETags that are not the MD5 of the object. Compare x-amz-checksum-sha256 or another full-object checksum instead. See Content addressing.

7 — Why does Go give every map its own random seed, and why must you not use hash/maphash to pick a shard? Good to know ​

Answer

Answer: The seed stops hash-flooding attacks where crafted keys pile into one bucket. Because it changes per process, the same key maps to different values on different machines and restarts, so shard routing would break. Use a fixed function (XXH3). See SipHash and seeded hashes.

8 — TLS 1.3 authenticates every record. Why do you still add x-amz-checksum-sha256 to an S3 upload? Important ​

Answer

Answer: TLS protects one session; the bytes are decrypted at proxies and buffered in processes before storage. The end-to-end checksum is computed by the producer and verified by S3 on the stored bytes, covering every hop. See In transit vs at rest.

9 — On your laptop BLAKE3 measured slower than SHA-256. Is the BLAKE3 README wrong? Good to know ​

Answer

Answer: No: speed belongs to an implementation on a CPU. The Go package used has SIMD assembly only for amd64, while ARMv8 has SHA-256 instructions. With the Rust/C implementation and SIMD, BLAKE3 is much faster. See Performance.

10 — What does a Docker image's layer digest hash, and what does its diff_id hash? Good to know ​

Answer

Answer: The layer digest is SHA-256 of the compressed blob (.tar.gz) as stored in the registry; the diff_id in the image config is SHA-256 of the uncompressed tar. See Byte-level view.

11 — Your PostgreSQL log shows page verification failed, calculated checksum … but expected …. What happened and what do you do? Important ​

Answer

Answer: A data page read from disk does not match its stored checksum: storage, controller or memory corruption. Check hardware, restore the affected relation from a replica or backup, and only use ignore_checksum_failure to salvage data. Monitor pg_stat_database.checksum_failures. See Bit rot.

12 — Why should you add a size check before hashing content from an untrusted registry, as the OCI spec suggests? Important ​

Answer

Answer: It rejects wrong-length content cheaply and narrows the collision space; an attacker must match both size and digest, and you avoid hashing an endless stream. See Content addressing.

Glossary ​

TermMeaning
ChecksumSmall redundant value computed from data to detect accidental changes
Hash functionMaps input of any length to a fixed-size output
DigestThe output of a cryptographic hash, e.g. sha256:…
ParityOne bit making the number of 1-bits even/odd; catches odd numbers of flips
Fletcher checksumTwo running sums modulo 255/65535; position-sensitive
Adler-32zlib's Fletcher variant with modulus 65521 (RFC 1950)
Internet checksum16-bit ones' complement sum used by IPv4, TCP, UDP (RFC 1071)
CRCCyclic redundancy check: remainder of polynomial division over GF(2)
Generator polynomialThe divisor that defines a CRC, e.g. 0x04C11DB7
CRC-32 (IEEE)Ethernet/gzip/zip/PNG CRC, reflected 0xEDB88320
CRC-32C (Castagnoli)iSCSI/Kafka/ext4/btrfs CRC, reflected 0x82F63B78
CRC-64/NVME64-bit CRC; S3's default checksum algorithm
Reflected CRCBits processed least-significant first
Hamming distance (HD)Minimum number of bit errors a code can miss
Burst errorErrors confined to a run of consecutive bits
SSE4.2 CRC32 / ARMv8 CRC32CXCPU instructions computing CRC-32C (and IEEE on ARM)
AvalancheOne input bit change flips about half the output bits
SMHasherTest suite for non-cryptographic hash quality
FNV-1aFowler–Noll–Vo hash: XOR byte then multiply by a prime
MurmurHash3Fast 32/128-bit non-cryptographic hash (Appleby)
CityHash / FarmHashGoogle's fast non-cryptographic string hashes
xxHash64 / XXH3 / XXH128Collet's very fast non-cryptographic hashes; XXH3 is the current default
SipHashKeyed fast PRF for hash tables (Aumasson & Bernstein)
Hash flooding / HashDoSDoS by sending keys that collide in a hash table
hash/maphashGo package exposing the runtime's seeded hash
SeedRandom per-process/table value mixed into a hash to make it unpredictable
MD5128-bit hash, collision-broken (RFC 6151)
SHA-1160-bit hash, collision-broken (SHAttered); NIST phase-out by 2030
SHAttered2017 practical SHA-1 collision by CWI and Google
SHA-2 (SHA-256, SHA-512)FIPS 180-4 Merkle–Damgård hash family
SHA-512/256, SHA-384Truncated SHA-512 variants; resist length extension
SHA-3 / KeccakFIPS 202 sponge-based hash family
SHAKE128/256SHA-3 extendable-output functions (XOF)
Sponge constructionAbsorb input into a rate part of a large state, permute, squeeze output; capacity stays hidden
Merkle–DamgårdIterated compression with length padding (MD5, SHA-1, SHA-2)
Length extensionComputing H(secret‖m‖pad‖x) from H(secret‖m) without the secret
BLAKE2Fast cryptographic hash (BLAKE2b/2s), RFC 7693
BLAKE3Tree-structured cryptographic hash; also MAC, KDF, XOF
Merkle treeTree of hashes where each parent hashes its children; root commits to all leaves
Preimage resistanceInfeasible to find any input for a given digest
Second-preimage resistanceInfeasible to find another input with the same digest as a given input
Collision resistanceInfeasible to find any two inputs with the same digest
Birthday boundCollisions expected after ~2^(n/2) random n-bit values
TruncationKeeping only some digest bits; security drops to those bits
HMACKeyed hash MAC: H((K⊕opad)‖H((K⊕ipad)‖m)) (RFC 2104)
Keyed hashHash with a secret key input (HMAC, keyed BLAKE3, SipHash)
MACMessage authentication code: integrity + authenticity with a shared key
AEADAuthenticated encryption with associated data; TLS 1.3 record protection
Constant-time compareComparison whose duration does not depend on where bytes differ
Content addressingNaming data by the hash of its bytes
git object idSHA-1/SHA-256 of "<type> <size>\0" + content
git hash-objectGit command printing (and with -w storing) an object id
OCI digestalgorithm:encoded string, e.g. sha256:…, naming a blob or manifest
diff_idSHA-256 of an uncompressed layer tar, listed in the image config
Image index / manifestOCI JSON documents listing platform manifests / config + layers by digest
Nix store path/nix/store/<base32 digest>-name, input- or content-addressed
IPFS CIDContent identifier: multibase + version + codec + multihash
MultihashSelf-describing hash format (algorithm code + length + digest)
ETagHTTP entity tag, an opaque validator of a representation
Weak ETagW/"…", semantic equivalence; not for If-Match
If-None-Match / 304Conditional GET; Not Modified response without body
If-Match / 412Conditional write; Precondition Failed when the tag changed
Content-MD5Legacy header with base64 MD5 of the body (S3 single-part)
x-amz-checksum-*S3 headers carrying base64 checksums for end-to-end verification
BadDigestS3 error: body does not match the supplied checksum
Full-object vs composite checksumS3 checksum of all bytes vs checksum of part checksums
Content-Digest / Repr-DigestRFC 9530 HTTP integrity fields
Subresource Integrity (SRI)integrity="sha384-…" attribute browsers verify for scripts/styles
rsync rolling checksumWeak sum updatable in O(1) per byte shift, paired with a strong hash
TCP checksum16-bit ones' complement; weak against real corruption patterns
End-to-end checksumComputed by producer, verified by final consumer
Bit rotGradual or silent corruption of stored data
Silent data corruptionWrong data returned without an I/O error
ScrubBackground read of all data to verify checksums and repair
ZFSFilesystem with per-block checksums in parent pointers and self-healing
btrfsLinux CoW filesystem with crc32c/xxhash/sha256/blake2 checksums
data_checksumsPostgreSQL read-only setting showing page checksums are on
pg_checksumsPostgreSQL tool to enable/disable/verify checksums offline
checksum_failurespg_stat_database column counting page checksum failures
ignore_checksum_failurePostgreSQL setting to read past checksum failures for salvage
CorruptRecordExceptionKafka error when a batch fails its CRC
DedupStoring identical content once, keyed by its hash
Unique indexDatabase constraint making a content hash column the single source of truth
Bloom filterProbabilistic set built from several hash functions (page)
Consistent hashingHash ring that limits key movement on resharding (page)
SaltPer-password random value for password hashing; not used for checksums
Hex / base64Text encodings of digest bytes: 2 chars per byte vs 4 chars per 3 bytes
io.TeeReaderGo reader that copies what it reads into a writer (e.g. a hash)
hash_file / hash_hmac / hash_equals / hash_update_streamPHP ext/hash functions for file digests, HMACs, constant-time compare and incremental stream hashing
Storage::checksumLaravel filesystem method (Flysystem 3.7+) returning a file checksum
Http::sinkLaravel HTTP client option streaming the response body to a file
createOrFirstEloquent insert-or-read that relies on a unique index

References ​

Built by Morteza Negahi