Secure String Comparator
Timing-safe string comparison to prevent timing attacks in security-sensitive operations
Compare Strings
Understanding Timing Attacks
What is a Timing Attack?
A timing attack exploits the time variations in cryptographic operations to extract secret information. By measuring how long operations take, attackers can infer data about secrets.
Insecure Comparison
Standard string comparison (===) returns early when a mismatch is found. This means comparing "abc" with "axx" takes less time than comparing with "abx", leaking prefix information.
Constant-Time Comparison
Secure comparison always takes the same time regardless of where differences occur. It compares all characters even after finding a mismatch.
Implementation
Use XOR operations and bitwise OR to accumulate differences without branching. In Node.js, use crypto.timingSafeEqual(). In browsers, implement manually.
Secure Comparison Implementation
function timingSafeEqual(a: string, b: string): boolean {
if (a.length !== b.length) {
// Still compare to avoid length-based timing leak
b = a;
}
let result = a.length ^ b.length;
for (let i = 0; i < a.length; i++) {
result |= a.charCodeAt(i) ^ b.charCodeAt(i);
}
return result === 0;
}Similar Tools
Explore more tools in this category