Definition
Constant-time comparison is a test of whether two byte strings of equal length are equal, in which the processor performs the same operations whatever the bytes contain, so the running time reveals nothing about where they differ. It is used to check secret values such as a message authentication code §5.7 tag, a short value that only a holder of a secret key can compute. The inputs are the two strings and their public length; the output is equal or not equal. An ordinary comparison stops at the first difference.
The idea
A receiver gets a message together with a 16-byte tag. It computes the tag the message should carry, called the expected tag, and compares it with the received tag, called the candidate. Suppose it uses the C library function memcmp. Typical implementations of memcmp compare from the first byte onward and return as soon as they find a difference. With a byte-by-byte comparison, a candidate whose first byte is wrong is rejected after one byte comparison, and a candidate whose first 5 bytes are right is rejected after 6. The difference in time is small, but an attacker who sends the same candidate many times and averages the response times §9.32 can detect it. Information that leaks through how long an operation takes is a timing side channel §1.29.
The attacker keeps the forged message fixed, so the expected tag stays the same, and varies only the candidate. The attacker tries all 256 values of the first byte; the value that is rejected most slowly is the right one. The attacker fixes that byte and repeats for the second byte, and so on. Recovering a 16-byte tag this way needs at most different candidates, each sent many times to average out noise, instead of a search among possible tags. The attacker ends with a valid tag for a message of the attacker’s choice and never learns the key.
The repair is to make the work independent of the contents: examine every byte position every time, and combine the results without ever branching on a byte’s value. A combination lock that clicks when one dial is set right can be opened one dial at a time; a lock that gives no signal until the whole combination is tried must be attacked by guessing the whole combination. The picture stops at one point. A constant-time comparison does reveal its final verdict, equal or not equal, because the receiver acts on it. What stays hidden is where the strings differ.
How it works
The usual method takes two byte strings and and their length . It uses an accumulator, a variable that collects a running result.
Check the lengths. The protocol fixes the length of a tag, so the length is public, and a candidate of any other length is rejected at once. That early exit reveals only the length, which the attacker already knows.
Set the accumulator to 0.
For every position from 0 to , compute the bitwise XOR (exclusive OR) of the two bytes and , and merge the result into with bitwise OR. The XOR of two bytes has a 1 bit exactly where the bytes differ, so it is 0 exactly when the bytes are equal. OR keeps every 1 bit that has ever been set, so once is nonzero it stays nonzero.
After the last position, report equal if and not equal otherwise.
In C the loop is
for (i = 0; i < n; i++) d |= a[i] ^ b[i];
where ^ is XOR and |= merges with OR. The loop runs times for every input. The addresses it reads depend only on , and its only branch, the loop test, depends only on and , never on a byte value.
Writing this loop is not enough by itself. The C standard defines what a program computes, not how long it takes, so a compiler may legally turn the loop into code that stops early, for instance as soon as holds 0xFF, after which no OR can change it. Library functions written for this purpose guard against such changes, for example by reading the bytes through pointers declared with the volatile qualifier §4.34, which forbids the compiler from skipping reads, or by writing the loop in assembly language. Examples are hmac.compare_digest in Python §12.23 and subtle.ConstantTimeCompare in the Go language. Calling such a function is safer than writing one’s own loop.
Worked example
Compare the 4-byte expected tag = 3a 7f 00 c4 with the candidate = 3a 7e 10 c4, each byte written in hexadecimal.
Position 0:
3aXOR3a=00, and =00OR00=00.Position 1:
7fXOR7e=01, because7fis01111111in binary and7eis01111110, which differ only in the last bit. Then =00OR01=01.Position 2:
00XOR10=10, and =01OR10=11.Position 3:
c4XORc4=00, and =11OR00=11.
The final is 11, which is not 0, so the tags are not equal. The OR at position 2 kept the difference found at position 1: 01 OR 10 has both 1 bits.
Had the candidate been 3a 7f 00 c4, every XOR would have been 00, would have ended at 00, and the verdict would have been equal. Either way the loop performed 4 XORs and 4 ORs. A byte-by-byte early-exit comparison would have stopped at position 1 for the candidate above, after 2 byte comparisons, but would have made 4 comparisons for a candidate that differs only in its last byte. That difference in the amount of work is what the attacker measures.
Stated precisely
Let be the public length, and let and be the bytes of the two strings. Write for bitwise XOR and for bitwise OR. The comparison computes and reports equal exactly when . The result is correct because holds exactly when , and an OR of bytes is 0 exactly when every one of them is 0.
The timing property belongs to the machine code running on a particular processor, not to the source text. The comparison runs in constant time with respect to the contents when three conditions hold for every and for all pairs of strings of length :
the same instructions run in the same order, which holds when no branch condition depends on any or ;
the same memory addresses are accessed, which holds when no address is computed from any or ;
each instruction used takes a time that does not depend on its operand values on that processor.
Under these three conditions the running time depends on alone. It still grows in proportion to : “constant” means the same for all contents of a given length, not the same for all lengths. The comparison may reveal and the verdict; it must reveal nothing else about the bytes, in particular not the position of the first difference.
Limits and common mistakes
A constant-time comparison does not hide the length of its inputs. The Python documentation for hmac.compare_digest states that if the two inputs have different lengths, or if an error occurs, a timing attack could in theory reveal their types and lengths, but not their values. The Go function subtle.ConstantTimeCompare is documented to return 0 at once when the lengths differ. This is safe because the length of a tag is public.
Compare against the full expected length. A verifier that compares only as many bytes as the candidate contains accepts a 1-byte candidate whose single byte matches, and an attacker finds that byte in at most 256 tries. Reject every candidate whose length differs from the expected length before comparing. Where a protocol uses tag truncation §5.12, the expected length is the agreed truncated length, never a length the sender chose.
The comparison protects only itself. The surrounding code can still leak through time: computing the expected tag, parsing the message before the check, logging the expected tag, or choosing between error paths for reasons that depend on secret data. Constant-time programming §5.36 applies the same rule to every operation on secret data.
A timing test that finds no measurable difference does not prove constant time. A better-placed attacker may measure more precisely, average more samples, or face a different processor or compiler version.
Constant time addresses timing only. The power a device draws and the electromagnetic signals it emits can depend on the values being combined, even when the time does not. Resisting an attacker who measures those needs further countermeasures, such as masking, which processes each secret value only in a form combined with a fresh random value.
Questions answered
Does the API also hide length, types, and surrounding control flow?
A constant-time comparison API does not hide the length or type of its inputs, nor the control flow around the call. A function such as Python’s hmac.compare_digest hides only the contents of its two inputs, in particular the position of the first difference, and only when both inputs have the same type and the same length. Its documentation states that if the lengths differ, or if an error occurs, for example because the two arguments have different types, a timing attack could in theory reveal the types and lengths of the inputs, though not their values. The function may return early in those cases. That is acceptable only when the length and type are public, as the length of a tag fixed by a protocol is.
The surrounding control flow belongs to the calling program, and no comparison function can control it: how the expected value is computed, what is parsed or logged before the check, which error paths run, and what happens after the verdict. Each of these must itself avoid branches and memory addresses that depend on secret data. The final verdict, equal or not equal, is revealed by design, because the receiver acts on it.
Related entries: Constant-time cryptographic implementation (§5.36), Tag truncation (§5.12), Compiler optimization (§3.39), Side channel (§1.29), Message authentication code (MAC) (§5.7), Bit operations: truth tables, masks, shifts, and rotations (§4.50), Volatile qualifier (§4.34). Further reading: [10].