How-To Guide

How to Implement Constant-Time Secret Comparison

Compare secrets without leaking timing: use constant-time functions, understand what they cover, and test that the comparison does not short-circuit.

On this page

  1. Introduction
  2. Identify where it matters
  3. Use a constant-time function
  4. Handle length differences safely
  5. Remember what constant time does not cover
  6. Test the non-short-circuit property
  7. Common pitfalls
  8. Conclusion

Introduction

Comparing a secret with an ordinary equality operator looks harmless and leaks information. Most implementations return as soon as they find a difference, so the time the comparison takes reveals how many leading bytes matched. An attacker who can measure that time, and who controls the value being compared, can recover the secret one byte at a time, using many attempts and statistics to beat the noise. This is a timing side channel, and it is subtle because the code looks correct.

This tutorial identifies where constant-time comparison is needed, shows how to compare secrets without an early return, handles differing lengths safely, and tests that the comparison does not short-circuit. The examples use standard library functions, which are the right tool rather than a hand-written loop that is easy to get wrong.

Identify where it matters

Constant-time comparison is needed when the value compared is a secret and the attacker controls the presented value or can influence it. Session tokens, one-time codes, HMAC signatures, password hashes, API keys, and any identifier that grants access fall in this class. Comparing two non-secret values, such as two timestamps or two public ids, does not need it.

Audit for the pattern of comparing an input to a stored or computed secret with == or equals. This includes verifying a webhook signature, checking a token, and validating a reset code. Each of those comparisons, if written with an ordinary equality, is a potential side channel, and the fix is the same everywhere: a constant-time comparison of fixed-length values.

Use a constant-time function

Standard libraries provide the primitive: Node.js has crypto.timingSafeEqual, Go has crypto/subtle.ConstantTimeCompare, and most languages have an equivalent. These compare two equal-length buffers and run in time independent of the contents, so the position of the first difference does not affect the duration. Use them instead of writing a loop, because a hand-written comparison that claims to be constant time usually is not, due to compiler optimizations or an early return.

Compare fixed-length values. If the secrets are variable length, hash each with the same algorithm to a fixed-length digest and compare the digests in constant time. The hash normalizes the length, so the comparison is over equal buffers, and it avoids a length-dependent branch. Hash the presented value and the stored value the same way, never one and not the other.

import { createHash, timingSafeEqual } from 'node:crypto';

function constantTimeEqual(a, b) {
  const ha = createHash('sha256').update(a).digest();
  const hb = createHash('sha256').update(b).digest();
  return timingSafeEqual(ha, hb); // fixed length, no early return
}

// verifying a presented token against the stored one
function tokenValid(presented, stored) {
  return constantTimeEqual(presented, stored);
}

Handle length differences safely

A constant-time comparison of fixed-length digests sidesteps the length problem, but if you compare the raw values and their lengths differ, you must not return early on the length. Instead, fold the length difference into the result, or reduce both to a fixed length by hashing, so the code takes the same path regardless. An early return on length is itself a leak of the length, though a minor one compared to a content leak.

The hash-first approach is the simplest and safest: it makes every comparison equal length and removes the branch entirely. The cost is one hash per comparison, which is negligible next to the network round trip. Prefer it to a manual length-handling branch, which has more ways to be subtly wrong.

package main

import (
    "crypto/subtle"
    "crypto/sha256"
)

// compare two variable-length secrets in constant time
func constantTimeEqual(a, b string) bool {
    ha := sha256.Sum256([]byte(a))
    hb := sha256.Sum256([]byte(b))
    return subtle.ConstantTimeCompare(ha[:], hb[:]) == 1
}

Remember what constant time does not cover

Constant-time comparison protects the comparison itself, not the surrounding logic. If you look up the secret in a way that takes longer for some inputs, or if you return a different error for a missing record than for a wrong secret, you leak through a different channel. In authentication, look up the record by a non-secret key first and always perform the comparison, even when the record is absent, comparing against a dummy value so the timing does not depend on existence.

Then avoid distinguishing errors that reveal account existence. Return the same error and the same timing whether the account is unknown or the secret is wrong. The constant-time comparison keeps the secret comparison from leaking; the uniform response keeps the surrounding flow from leaking. Both are needed for a uniform authentication path.

async function authenticate(username, presentedSecret) {
  const row = await lookup(username);
  // always compare, even when the row is absent, against a fixed dummy hash
  const stored = row ? row.secret_hash : DUMMY_HASH;
  const ok = constantTimeEqual(presentedSecret, stored);
  if (!ok || !row) return null;   // same path and result for both cases
  return row;
}

Test the non-short-circuit property

Testing timing directly is noisy, so test the property at the unit level by instrumenting the comparison to count how many byte positions it examined. For a mismatch at the first byte and a mismatch at the last byte of equal-length values, the count must be the same, which proves there was no early return. This is a deterministic test of the property, unlike a wall-clock measurement.

Also test that equal values return true, that different-length inputs do not throw or short-circuit, and that the function is used at every secret comparison site through a lint rule or a code review checklist. A single ordinary equality left in a token check reintroduces the leak, so the coverage matters as much as the implementation.

# unit-level property test: count examined positions, not wall-clock time
node -e '
const equal = require("./constant-time-equal");
// instrumented variant records examined bytes; both must equal the full length
'

Common pitfalls

Using == or equals on a secret, a hand-written loop with an early return, comparing a hash to a raw value so the lengths differ, returning early on a length mismatch, and distinguishing a missing account from a wrong secret are the recurring mistakes. Standard-library constant-time functions, fixed-length digests, no length branch, and a uniform response address them.

Conclusion

A secret compared with ordinary equality leaks through timing. Use the standard library’s constant-time comparison on fixed-length values, hash variable-length secrets first, never branch on length or content, and keep the surrounding flow uniform so existence does not leak either. Self-check by asserting that rejecting an early mismatch and a late mismatch examines the same number of positions. Then the comparison stops being a channel an attacker can read.

Sources: OWASP: Authentication cheat sheet, Node.js: crypto.timingSafeEqual, Go: crypto/subtle ConstantTimeCompare.

FAQ

Why does ordinary string equality leak?
Most equality implementations return at the first differing byte, so the time to reject depends on how many leading bytes matched. An attacker who measures that time can recover a secret one byte at a time, especially over many attempts on a network where the difference is measurable.
Do I need constant time everywhere?
Only where the compared value is secret and the attacker controls the presented value. Comparing two public values or two non-secrets does not need it. Focus on tokens, HMACs, password hashes, API keys, and reset codes.

Related Examples