Skip to main content

Timing-safe comparison: HMACs, API keys and the == that leaks

Most webhook and API key checks end with one line: compare what the caller sent with what you expected. Written as if (sent === expected), that line usually stops at the first byte that differs. A wrong guess that matches the first ten characters takes slightly longer to reject than one that matches none, and that difference is a signal an attacker can measure.

Exploiting it over a network takes many samples, and jitter makes it noisy. The fix, though, is a single function call that exists in every mainstream language, so there is no reason to argue about exploitability. GitHub's webhook validation docs put it plainly: never use a plain == operator. This post covers why, the right call in each language, and the mistakes that survive even after you switch.

How an ordinary comparison leaks

String and byte comparisons are optimised to return as soon as they find a difference. For a secret, that turns one impossible guess into many easy ones. Instead of guessing a 64-character hex signature all at once (16 to the power of 64 possibilities), an attacker guesses the first character, keeps the one that takes longest to reject, and moves to the next: at most 16 candidates per position, 1,024 candidates in total, each repeated enough times to average out the noise.

A constant-time comparison inspects every byte regardless of where the first difference is, so its running time depends only on the length of the inputs.

The right function in each language

Language Constant-time compare Notes
Node.js crypto.timingSafeEqual(a, b) Buffers or typed arrays; throws if lengths differ
Python hmac.compare_digest(a, b) Also secrets.compare_digest; str arguments must be ASCII
Go subtle.ConstantTimeCompare(x, y), hmac.Equal Returns 0 immediately if lengths differ
Java MessageDigest.isEqual(a, b) Time depends only on the length of the first argument
PHP hash_equals($known, $user) Known string first
Ruby ActiveSupport::SecurityUtils.secure_compare, Rack::Utils.secure_compare

The Node.js docs describe timingSafeEqual as suitable for HMAC digests, authentication cookies and capability URLs. The Java docs note that isEqual examines all bytes of the first argument and that its time does not depend on the contents.

Verifying a webhook signature

Node.js, with the raw request body:

const crypto = require("node:crypto");

function verifySignature(rawBody, header, secret) {
  if (typeof header !== "string" || !header.startsWith("sha256=")) return false;
  const expected = "sha256=" + crypto.createHmac("sha256", secret).update(rawBody).digest("hex");
  const a = Buffer.from(header, "utf8");
  const b = Buffer.from(expected, "utf8");
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

The length check before timingSafeEqual is required, because the function throws when lengths differ. It leaks only the length, which for a fixed-format signature is public anyway.

Python:

import hashlib
import hmac

def verify_signature(body: bytes, header: str, secret: bytes) -> bool:
    expected = "sha256=" + hmac.new(secret, body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected.encode(), header.encode())

hmac.compare_digest accepts str only when it is ASCII and raises TypeError otherwise, so an attacker who sends a non-ASCII header turns your verifier into a 500. Encoding both sides to bytes avoids that.

Java:

import java.security.MessageDigest;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

static boolean verify(byte[] body, String header, byte[] secret) throws Exception {
    if (header == null || !header.startsWith("sha256=")) return false;
    byte[] sent;
    try {
        sent = HexFormat.of().parseHex(header.substring("sha256=".length()));
    } catch (IllegalArgumentException e) {
        return false;
    }
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(secret, "HmacSHA256"));
    return MessageDigest.isEqual(mac.doFinal(body), sent);
}

API keys: compare hashes, not the key

For API keys, the best pattern also fixes storage. Give each key a public id and a secret part, store only a hash of the secret, look the key up by id, and compare hashes in constant time:

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

// Key format: "vk_<id>_<secret>". The database stores id and sha256(secret).
func secretMatches(presentedSecret string, storedHash []byte) bool {
	sum := sha256.Sum256([]byte(presentedSecret))
	return subtle.ConstantTimeCompare(sum[:], storedHash) == 1
}

Hashing first gives both sides the same fixed length, so subtle.ConstantTimeCompare, which returns 0 immediately for different lengths, never takes that shortcut. Looking up by id instead of by the secret keeps the secret out of database indexes and query logs, and a stolen table holds no working keys.

Traps that survive the switch

Loose equality and missing values. In JavaScript, == treats null and undefined as equal:

// If INTERNAL_TOKEN is unset and the header is missing: undefined == undefined is true
if (req.headers["x-internal-token"] == process.env.INTERNAL_TOKEN) return next();

An unset environment variable plus an omitted header passes the check. Fail closed first: if the configured secret is missing or empty, refuse every request, then require the presented value to be a non-empty string, then compare in constant time.

Comparing the wrong representations. Hex digests in different cases, base64 with and without padding, or a prefix like sha256= on one side only will never match, and the usual "fix" is a normalising step written with ordinary string functions. Normalise the format of the value you computed, decode the presented value strictly, and compare bytes.

Leaks around the comparison. Node's docs warn that using timingSafeEqual does not make the surrounding code timing-safe. Early returns that depend on the secret, such as checking a prefix of the stored key before the real comparison, reintroduce the signal.

Passwords. Do not compare password hashes yourself. Use the verify function of your password hashing library (bcrypt, scrypt or Argon2), which handles the comparison.

Short codes. A six-digit OTP compared in constant time is still guessable by brute force. Its protection is a short expiry and a strict attempt limit per account.

Review checklist

  • Grep for ==, ===, .equals(, strcmp and != on lines that mention signature, hmac, token, secret, apiKey or digest.
  • Check every webhook handler: raw body, HMAC computed on the server, constant-time comparison, and a timestamp or replay check if the sender provides one.
  • Check what happens when the configured secret is missing.
  • Check that API keys are stored hashed and looked up by a non-secret id.

Finding timing leaks with Vulkro

Vulkro Core flags direct comparisons of secret-named values and the null-equality bypass:

vulkro scan . --format json > findings.json
vulkro explain non-constant-time-secret-compare
Rule What it flags
non-constant-time-secret-compare == or != between a strongly secret-named value (token, signature, HMAC, API key, OTP, CSRF token) and another value, in JavaScript, TypeScript, Python and Go
non-constant-time-compare A secret compared with request data using == in Python, JavaScript or TypeScript
java-timing-compare-equals, java-timing-compare-operator String.equals, Arrays.equals, == or != on a security-named value in Java
loose-equality-secret-null-bypass A stored secret compared loosely to an optional request field, the null == undefined bypass
c-hardcoded-credential-compare A hardcoded credential compared in C

A plain password comparison on a form is deliberately not in the secret list, because that is usually a library call or noise, while password_hash compared with == is. If the line already calls a constant-time comparator, nothing is reported.

FAQ

Why should I use timingSafeEqual instead of ===?

=== stops at the first differing character, so the time it takes reveals how much of a guess was right. crypto.timingSafeEqual takes the same time regardless of where the inputs differ, which removes that signal. Check the lengths first, because it throws on different lengths.

Is hmac.compare_digest safe with strings?

Yes, if both are ASCII strings of the same type. It raises TypeError for non-ASCII str, so encode untrusted input to bytes first. Different lengths may leak the length, but not the value.

Are timing attacks on string comparison practical over a network?

They need many samples and are hurt by network jitter, but an attacker close to the server (the same cloud region or the same host) sees far less noise, and the samples are cheap to collect. The fix is one function call, so treat it as a requirement rather than a risk to weigh.

See the API security use case and the secrets detection docs, or start a 14-day trial. Related: unsigned webhooks and request bodies written to the database and insecure randomness.