Constant-Time String Comparison
Compare secrets without early exit by XOR-ing UTF-8 bytes, reducing timing leaks in token and signature checks.
Code
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
HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.