Constant-Time String Comparison

Compare secrets without early exit by XOR-ing UTF-8 bytes, reducing timing leaks in token and signature checks.

JavascriptSecurity Boundaries

Code

javascriptsnippet
25 lines
const encoder = new TextEncoder();

// Constant-time comparison for secrets and signatures.
export function constantTimeEqual(left, right) {
  const a = encoder.encode(String(left));
  const b = encoder.encode(String(right));
  const length = Math.max(a.length, b.length);
  let difference = a.length ^ b.length;
  for (let index = 0; index < length; index += 1) {
    difference |= (a[index] ?? 0) ^ (b[index] ?? 0);
  }
  return difference === 0;
}

export function constantTimeEqualBytes(left, right) {
  if (!(left instanceof Uint8Array) || !(right instanceof Uint8Array)) {
    throw new TypeError("both arguments must be Uint8Array values");
  }
  const length = Math.max(left.length, right.length);
  let difference = left.length ^ right.length;
  for (let index = 0; index < length; index += 1) {
    difference |= (left[index] ?? 0) ^ (right[index] ?? 0);
  }
  return difference === 0;
}

How the snippet works

Constant-Time String Comparison comes down to the functions constantTimeEqual and constantTimeEqualBytes.

Invalid states are rejected up front: it throws TypeError instead of continuing with bad data.

Applying it

The primary signature is export function constantTimeEqual(left, right)

Import constantTimeEqual from the file and call it — the rest of the code is implementation detail.

Statements that matter

throw new TypeError("both arguments must be Uint8Array values");
difference |= (left[index] ?? 0) ^ (right[index] ?? 0);
for (let index = 0; index < length; index += 1) {
  difference |= (a[index] ?? 0) ^ (b[index] ?? 0);
}

Interactive Tools for This Topic

FAQ

How are precondition violations signaled?
`TypeError` is raised at the guard, so invalid state never reaches the main logic.
Are there dependencies to manage?
No. There are no dependencies to declare or install. The file defines `constantTimeEqual`, `constantTimeEqualBytes` at load time.