QUICK START:PatternsErrors & FixesSecurityBenchmarksDevOps RecipesCheatsheetsInterviewCompareTopicsHTMLCSSJavaScriptTypeScriptPythonSQLReactNext.jsNode.jsLinux & UbuntuKotlinSwiftC# / .NETJavaGoRustC++DSASystem DesignDevOpsCybersecurityAI / ML
Medium ThreatCryptography & ProtocolsCWE-208

Constant-Time Cryptographic Comparison Defense

Defend against side-channel timing attacks by implementing constant-time cryptographic string comparisons.

Vulnerability Overview

Early exit in string comparison leaks information about the secret.

Attackers measure response times to guess hashes character by character.

Vulnerable Code

if (userInput === secretToken) { /* success */ }

Fails fast on the first mismatched character.

Remediated Code

crypto.timingSafeEqual(Buffer.from(input), Buffer.from(secret))

Compares in constant time regardless of mismatches.

Hardening Rules

  • 1Use crypto.timingSafeEqual
  • 2Avoid simple equality checks for secrets

Frequently Asked Questions

Why does normal equality leak data?

Because it stops checking as soon as it finds a mismatch, revealing how many characters matched.