liveBook · Manning

Constant-time comparison

As explained in Real-World Cryptography

A constant-time comparison compares two values in an execution pattern whose duration does not depend on the location of their first difference.

When a server checks an authentication tag, an early exit can reveal where the first incorrect byte appears. An attacker can use these timing differences to reconstruct a valid tag byte by byte. A constant-time comparison follows the same execution pattern for equal-sized inputs, regardless of where they differ. section 3.3.4

A practical comparison pattern:

  • Reject inputs with different lengths. section 13.4.1
  • Process every corresponding byte without branching on equality. section 13.4.1
  • XOR each pair and OR the results; zero means all compared bytes matched, while a nonzero result indicates a difference. section 13.4.1

Authentication-tag verification

Recompute a MAC tag, then compare it with the received tag using a cryptographic library’s constant-time verification function. Do not use an ordinary comparison that returns as soon as it finds a mismatch. section 3.3.4 section 3.7

Listing 13.1 How Golang implements a constant-time comparison between two bytearrays
func ConstantTimeCompare(x, y []byte) byte {
    if len(x) != len(y) {                        #1
        return 0                                 #1
    }                                            #1
 
    var v byte                                   #2
    for i := 0; i < len(x); i++ {                #2
        v |= x[i] ^ y[i]                         #2
    }                                            #2
 
    return v                                     #3
}

The Go pattern checks length, accumulates every byte difference, and returns the accumulated result after the loop. section 13.4.1

How Real-World Cryptography covers it

How deep it goes
Explains branch avoidance and XOR-OR accumulation, while leaving the exact trick as an exercise.
Examples
Uses MAC tag verification and Go byte-array comparison with XOR and OR accumulation.
What it assumes
Assumes familiarity with message authentication codes, authentication tags, and comparing byte sequences.
What you can do after
Apply it via cryptographic library verification functions when comparing received and computed authentication tags.
How it connects
Connects authentication tags, message authentication codes, timing attacks, cache attacks, and simple power analysis attacks.

Also explained in

Compare how 2 books explain constant-time comparison →

Related concepts

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