constant-time.ts

823 B · raw

1/**2 * Compare fixed-format cryptographic values without data-dependent early exit.3 *4 * Length remains observable, so callers should validate public wire formats5 * first. Peach's keys and tokens have fixed lengths at every authenticated6 * comparison site.7 */8export function constantTimeEqualBytes(9  left: Uint8Array,10  right: Uint8Array,11): boolean {12  let difference = left.length ^ right.length;13  const length = Math.max(left.length, right.length);14  for (let index = 0; index < length; index += 1) {15    difference |= (left[index] ?? 0) ^ (right[index] ?? 0);16  }17  return difference === 0;18}1920export function constantTimeEqualHex(left: string, right: string): boolean {21  return constantTimeEqualBytes(22    new TextEncoder().encode(left.toLowerCase()),23    new TextEncoder().encode(right.toLowerCase()),24  );25}