Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

constantTimeCompare

Compares two strings in constant time to prevent timing attacks.

TypeScript
Copied!
1/**
2 * Compares two strings in constant time to prevent timing attacks.
3 *
4 * @param a - First string to compare.
5 * @param b - Second string to compare.
6 * @returns True if strings are equal, false otherwise.
7 */
8export function constantTimeCompare(a: string, b: string): boolean {
9  if (a.length !== b.length) return false;
10
11  let result = 0;
12  for (let i = 0; i < a.length; i++) {
13    result |= a.charCodeAt(i) ^ b.charCodeAt(i);
14  }
15
16  return result === 0;
17}
  • Prevents Timing Attacks

    Designed to execute in constant time regardless of input, mitigating the risk of attackers inferring string values based on execution duration.

  • Bitwise Comparison Logic

    Uses XOR and bitwise OR to accumulate differences, ensuring the loop runs fully even if characters differ early on.

  • Early Length Check Optimization

    Short-circuits clearly unequal inputs by comparing string lengths first — a safe and efficient pre-check.

  • Minimal Overhead

    Pure JavaScript with no dependencies, ensuring high performance and easy portability.

Tests | Examples

TypeScript
Copied!
1test('returns true for equal strings', () => {
2  expect(constantTimeCompare('secure', 'secure')).toBe(true);
3});
4
5test('returns false for different strings', () => {
6  expect(constantTimeCompare('secure', 'insecure')).toBe(false);
7});
8
9test('returns false for strings with same prefix', () => {
10  expect(constantTimeCompare('token123', 'tokenXYZ')).toBe(false);
11});
12
13test('returns false for strings with different lengths', () => {
14  expect(constantTimeCompare('abc', 'abcd')).toBe(false);
15});
16
17test('returns true for empty strings', () => {
18  expect(constantTimeCompare('', '')).toBe(true);
19});

Common Use Cases

  • Verifying Cryptographic Signatures

    Safely compare HMACs, token hashes, or digital signatures where timing leaks can be exploited.

  • Comparing Authentication Secrets

    Check API keys, session tokens, or password hashes in authentication flows.

  • Secure Equality Checks in Webhooks

    Compare shared secrets sent in headers (e.g., X-Hub-Signature) without leaking information through timing.

  • Validating JWT or OAuth Tokens

    Confirm sensitive values like access tokens match expectations in a secure manner.

Codebase: Utilities -> Encoding -> constantTimeCompare | Yevhen Klymentiev