Secrets, cryptography and supply chain · 5 MIN READ
Compare secrets in constant time: an early return reveals how much of a guess was right
Recognize timing-dependent comparisons and replace them with crypto/subtle or hmac.Equal over fixed-size digests, including the lookup and error paths around them.
A comparison that stops at the first differing byte takes longer the more of the guess is correct. Against a token, an API key or a MAC tag, that turns an impossible search over the whole value into a byte-by-byte search an attacker can run with enough repeated requests. Constant time here means time that depends only on public facts, such as the length, and never on the contents of the secret.
security · A MAP OF THE IDEA
- Hash to a fixed length
- Look up by public ID
- Compare with crypto/subtle
- Return one error
Useful when
- Removes the per-byte oracle that makes long tokens guessable.
- Digest comparison also hides the length and lets you store only hashes.
Watch out
- ConstantTimeCompare returns immediately when lengths differ.
- Lookups, error messages and metrics around the comparison can still leak.
Implementation & operation cost: One hash and a full-length comparison per check, negligible next to a network round trip. The real cost is reviewing the surrounding path, which tests cannot do for you.
Why an early return is an oracle
To guess a 20-byte token blindly, an attacker faces 256^20 candidates. If the server's comparison returns as soon as one byte differs, each response time hints at how many leading bytes were right. The attacker then fixes one position at a time: at most 256 candidates per byte across 20 bytes, a few thousand guesses, each repeated enough times to average out network noise. The difference per byte is tiny, but repeated measurements from a nearby network position, such as another tenant in the same cloud region, can resolve it. Go's == on strings and bytes.Equal make no timing promise and do stop early, so they are the wrong tool for secrets even though they are the right tool for everything else.
Measure the work instead of the nanoseconds
Timing is noisy in a demo, so the program counts the bytes a naive loop examines, which is what its running time tracks. It then shows the standard tools: subtle.ConstantTimeCompare for equal-length values, a SHA-256 digest step that removes the length signal, and hmac.Equal for MAC tags computed with a test-only key.
package main
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"fmt"
)
// naiveEqual mirrors a hand-written loop (and what == may do): it stops at
// the first mismatch. steps counts the bytes examined, a stand-in for time.
func naiveEqual(a, b []byte) (equal bool, steps int) {
if len(a) != len(b) {
return false, 0
}
for i := range a {
steps++
if a[i] != b[i] {
return false, steps
}
}
return true, steps
}
// tokenMatches hashes both sides first, so the comparison always runs over
// two 32-byte digests no matter how long the presented token is.
func tokenMatches(presented string, storedDigest [32]byte) bool {
d := sha256.Sum256([]byte(presented))
return subtle.ConstantTimeCompare(d[:], storedDigest[:]) == 1
}
func main() {
secret := []byte("tok_4f9c2a7e81b3d605") // a test token, 20 bytes
guesses := []string{
"xxxxxxxxxxxxxxxxxxxx", // nothing right
"tok_xxxxxxxxxxxxxxxx", // public prefix right
"tok_4f9c2axxxxxxxxxx", // ten bytes right
"tok_4f9c2a7e81b3d605", // all right
}
for _, g := range guesses {
eq, steps := naiveEqual(secret, []byte(g))
fmt.Printf("naive %s equal=%-5t bytes examined=%d\n", g, eq, steps)
}
// Equal-length inputs: work depends only on the length.
fmt.Println("subtle full match:", subtle.ConstantTimeCompare(secret, []byte(guesses[3])))
fmt.Println("subtle ten bytes right:", subtle.ConstantTimeCompare(secret, []byte(guesses[2])))
// Different lengths return 0 immediately: the length itself can leak.
fmt.Println("subtle short guess:", subtle.ConstantTimeCompare(secret, []byte("tok_")))
stored := sha256.Sum256(secret)
fmt.Println("digest match:", tokenMatches("tok_4f9c2a7e81b3d605", stored))
fmt.Println("digest short guess:", tokenMatches("tok_", stored))
key := []byte("test-only-hmac-key-0123456789abc")
mac := func(msg string) []byte {
m := hmac.New(sha256.New, key)
m.Write([]byte(msg))
return m.Sum(nil)
}
received := mac("order=42;amount=1999")
fmt.Println("hmac.Equal valid:", hmac.Equal(mac("order=42;amount=1999"), received))
fmt.Println("hmac.Equal altered:", hmac.Equal(mac("order=42;amount=1"), received))
fmt.Println("hmac.Equal truncated:", hmac.Equal(mac("order=42;amount=1999"), received[:16]))
}The naive loop examines 1, 5, 11 and 20 bytes: its work grows with the correct prefix, and that growth is the oracle. subtle.ConstantTimeCompare XORs every byte pair and ORs the results, so for equal lengths its work does not depend on content; it returns the int 1 or 0, not a bool. The short guess returns 0 immediately, because the documented guarantee covers contents, not length. tokenMatches hashes the presented value first, so every comparison runs over two 32-byte digests whatever the caller sends. hmac.Equal is ConstantTimeCompare(...) == 1; the truncated tag fails because its length differs.
Fixed-size digests close the length channel
ConstantTimeCompare returns at once when lengths differ, and its documentation says so. For tokens you issue in a fixed format, the length is public anyway. For values whose length is secret or chosen by someone else, such as a shared webhook secret or a legacy API key, compare digests: SHA-256 of either side is always 32 bytes. Hashing also lets you store only the digest, so a database read does not hand out working credentials; the token-design lesson builds on that. A fast hash is enough only for high-entropy values. Passwords need the slow, salted hashing of the password-storage lesson, because a fast digest of a guessable value is itself guessable. For MAC tags, compute the expected tag over the received message and compare the full length: code that compares only as many bytes as the client sent accepts a one-byte tag after at most 256 tries.
The comparison is not the only branch
A constant-time compare inside a variable-time path still leaks. Look at the code around it: a lookup that returns early when a key ID is unknown, a database query with the secret in its WHERE clause, different messages or status codes for no such key and wrong key, and metrics labeled by failure reason all reveal information. Look credentials up by a public identifier or by the digest of the secret, compare in constant time, and return one generic error. When the identifier is unknown, compare against a dummy digest so both paths do the same work.
func (s *KeyStore) Authenticate(keyID, presented string) (Principal, error) {
got := sha256.Sum256([]byte(presented))
rec, found := s.byID[keyID] // keyID is public, e.g. the prefix of the API key
want := s.dummy // a random digest, so unknown IDs do the same work
if found {
want = rec.Digest
}
if subtle.ConstantTimeCompare(got[:], want[:]) != 1 || !found {
return Principal{}, errUnauthorized // one error for every failure
}
return rec.Principal, nil
}This fragment shows the shape of an API key check; KeyStore, Principal and errUnauthorized belong to your service, and it runs in your own environment. The map lookup by a public key ID may take variable time because the ID is not secret. Both branches hash and compare, and the found check comes after the comparison, so an unknown ID and a wrong secret are indistinguishable in both result and work.
Review it; do not try to benchmark it
Unit tests cannot prove constant time, and a benchmark that shows equal averages on a laptop says little about a loaded production CPU. Treat it as a review rule instead: every comparison of a token, MAC, API key, signature or password hash uses subtle.ConstantTimeCompare, hmac.Equal or a library verifier that does, over fixed-length inputs, followed by a single error path. Search for == and bytes.Equal near names such as token, secret, signature and digest. On arm64, subtle.WithDataIndependentTiming (Go 1.24) enables the processor's data-independent-timing mode for code that is already written in constant time; it does not repair variable-time code, and most services do not need it. Rate limiting the endpoint helps as well, because the attack needs many requests.
TAKE THIS WITH YOU
Compare secrets with crypto/subtle or hmac.Equal over fixed-size digests, look them up by a public ID or by their hash, and give every failure the same error and the same amount of work.
Check your understanding
Comparing a presented API token with == returns the right answer. Why is it still a vulnerability?
Go to the source
Progress stays in this browser. No account needed.