liveBook · Manning

Memcmp

As explained in Hacking Cryptography

memcmp is a C standard-library function that compares two memory regions and reports the first differing byte or equality.

memcmp compares two memory regions byte by byte, returning zero when they match and a nonzero value based on the first differing byte. Its early exit is dangerous for cryptographic values: the elapsed time reveals how many leading bytes matched. section 10.4.1

Early-exit comparison

A glibc implementation repeatedly loads corresponding bytes, advances both pointers, and continues only while they are equal. The first mismatch exits the loop and returns a0 - b0, so longer matching prefixes take longer to compare. section 10.4.1

Use constant-time comparison for secrets instead: scan every byte, accumulate differences with XOR, and decide equality only after the scan. Go's crypto/subtle implementation returns 1 for equal-length equal slices and 0 otherwise. section 10.4.1

How Hacking Cryptography covers it

How deep it goes
Traces glibc's byte loop and contrasts its short circuit with XOR-based constant-time comparison.
Examples
Uses glibc's memcmp_bytes loop and Go's crypto/subtle ConstantTimeCompare as contrasting implementations.
What you can do after
Diagnose timing leakage in short-circuit comparisons and select an explicitly constant-time alternative for secret data.
How it connects
Connects memcmp to constant-time comparison, timing side channels, cryptographic implementations, and standard libraries.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Hacking Cryptography. The section links point to the parts of the book it draws on.