QA
Senior LevelAuthentication & Authorization

How do you write Constant-Time String Comparison functions to defend against Timing Side-Channel Attacks?

❓ Interview Prompt: Explain Timing Side-Channel Attacks, early-exit string comparisons, crypto.timingSafeEqual, and constant-time execution.

Standard string equality comparisons ('strA === strB') return 'false' on the very first non-matching byte/character (early-exit optimization). This opens severe Timing Side-Channel Vulnerabilities.

How Timing Attacks Work:

An attacker measures high-precision HTTP response timing (microseconds). If guessing a secret token byte-by-byte:

•
Guessing 'a...' returns in 1.1ms (first byte fails).
•
Guessing 'x...' returns in 1.4ms (first byte matches, second byte fails!).

By measuring execution time differences, the attacker guesses secrets character by character!

Mitigation:

Constant-Time Comparisons: Functions process every byte in memory regardless of match status, taking identical CPU time.

Code Implementation Example

typescript
import crypto from 'crypto';

// SECURE: Constant-time string comparison function
function safeCompareTokens(a: string, b: string): boolean {
  const bufA = Buffer.from(a, 'utf-8');
  const bufB = Buffer.from(b, 'utf-8');

  // Prevent length mismatch timing leaks by comparing against fixed length
  if (bufA.length !== bufB.length) {
    crypto.timingSafeEqual(bufA, bufA); // Perform dummy constant-time operation
    return false;
  }

  return crypto.timingSafeEqual(bufA, bufB); // Constant-time CPU execution
}
💡Constant-time string comparison using crypto.timingSafeEqual to prevent timing side-channel attacks.
🎯 Interview Key Takeaway

Use constant-time comparison functions (crypto.timingSafeEqual) to prevent attackers from discovering secret tokens via timing side-channels.

#Constant-Time#Timing Attack#Side-Channel#Crypto#Senior
Back to all Authentication & Authorization Questions→

More Authentication & Authorization Interview Questions

Beginner LevelAuthentication & Authorization

Compare JWT Token Authentication versus Stateful Sessions, and explain OAuth 2.0 PKCE flow.

Beginner LevelAuthentication & Authorization

What is the fundamental difference between Authentication (AuthN) and Authorization (AuthZ)?

Beginner LevelAuthentication & Authorization

Why should passwords never be stored in plain text and how do bcrypt and Argon2id work?