hash_equals
hash_equals(string $known_string, string $user_string): bool
Timing-safe (constant-time) string comparison to prevent timing attacks — the mandatory way to compare MACs, hashes and tokens.
C C23
#include <stdio.h>
#include <string.h>
/* Constant-time comparison idiom: accumulate differences with XOR, length mismatch included — an early return leaks comparison progress byte by byte */
static int ct_equal(const char *a, const char *b) {
size_t la = strlen(a), lb = strlen(b);
size_t n = la < lb ? la : lb;
unsigned char diff = (unsigned char)(la ^ lb);
for (size_t i = 0; i < n; i++) {
diff |= (unsigned char)(a[i] ^ b[i]);
}
return diff == 0;
}
int main(void) {
const char *known = "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7";
const char *good = "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7";
const char *evil = "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb8";
printf("%d\n", ct_equal(known, good));
printf("%d\n", ct_equal(known, evil));
printf("%d\n", ct_equal(known, "10aa2e1c25")); /* Length mismatch → false */
printf("%d\n", strcmp(known, good) == 0); /* strcmp is not constant-time — never use it in security contexts */
return 0;
}
1 0 0 1
C++ C++26
#include <cstring>
#include <iostream>
#include <string>
// Constant-time comparison idiom: accumulate differences with XOR, length mismatch included — an early return leaks comparison progress byte by byte
static bool ct_equal(const std::string &a, const std::string &b) {
size_t n = std::min(a.size(), b.size());
unsigned char diff = static_cast<unsigned char>(a.size() ^ b.size());
for (size_t i = 0; i < n; i++) {
diff |= static_cast<unsigned char>(a[i] ^ b[i]);
}
return diff == 0;
}
int main() {
const std::string known = "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7";
const std::string good = "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7";
const std::string evil = "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb8";
std::cout << std::boolalpha;
std::cout << ct_equal(known, good) << "\n";
std::cout << ct_equal(known, evil) << "\n";
std::cout << ct_equal(known, evil.substr(0, 10)) << "\n"; // Length mismatch → false
std::cout << (known == good) << "\n"; // == is not constant-time — never use it in security contexts
return 0;
}
true false false true
C# v11.0.100
using System.Security.Cryptography;
// CryptographicOperations.FixedTimeEquals: constant-time comparison (.NET Core 2.1+); a length mismatch returns false without throwing
byte[] known = Convert.FromHexString("10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7");
byte[] good = Convert.FromHexString("10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7");
byte[] evil = Convert.FromHexString("10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb8");
Console.WriteLine(CryptographicOperations.FixedTimeEquals(known, good));
Console.WriteLine(CryptographicOperations.FixedTimeEquals(known, evil));
Console.WriteLine(CryptographicOperations.FixedTimeEquals(known, evil[..10]));
Console.WriteLine(known.SequenceEqual(good)); // SequenceEqual is not constant-time — never use it in security contexts
True False False True
Go v1.27.4
package main
import (
"crypto/subtle"
"fmt"
)
func main() {
// subtle.ConstantTimeCompare: constant-time comparison — 1 for equal, 0 for different (length mismatch is 0 too, no error)
known := "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7"
good := "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7"
evil := "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb8"
fmt.Println(subtle.ConstantTimeCompare([]byte(known), []byte(good)))
fmt.Println(subtle.ConstantTimeCompare([]byte(known), []byte(evil)))
fmt.Println(subtle.ConstantTimeCompare([]byte(known), []byte(evil[:10])))
fmt.Println(known == good) // == is not constant-time — never use it in security contexts
}
1 0 0 true
Java v27.0.1
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// MessageDigest.isEqual: constant-time comparison — before JDK 6u17 it was a non-constant-time early-return implementation (a historical vulnerability)
byte[] known = "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7".getBytes(StandardCharsets.UTF_8);
byte[] good = "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7".getBytes(StandardCharsets.UTF_8);
byte[] evil = "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb8".getBytes(StandardCharsets.UTF_8);
System.out.println(MessageDigest.isEqual(known, good));
System.out.println(MessageDigest.isEqual(known, evil));
System.out.println(MessageDigest.isEqual(known, Arrays.copyOf(evil, 10))); // Length mismatch → false
System.out.println(Arrays.equals(known, good)); // Arrays.equals is not constant-time — never use it in security contexts
}
}
true false false true
JavaScript v26.13.1
const { timingSafeEqual } = require("node:crypto");
// timingSafeEqual: constant-time comparison — but a length mismatch throws RangeError outright (the only one of the ten languages that throws)
const known = Buffer.from("10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7", "hex");
const good = Buffer.from("10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7", "hex");
const evil = Buffer.from("10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb8", "hex");
console.log(timingSafeEqual(known, good));
console.log(timingSafeEqual(known, evil));
try {
timingSafeEqual(known, evil.subarray(0, 10));
} catch {
console.log("length mismatch -> throws");
}
console.log(known.equals(good)); // equals is an ordinary comparison (not constant-time) — never use it in security contexts
true false length mismatch -> throws true
PHP v8.6.0
// hash_equals: the mandatory way to compare MACs/hashes in constant time — == and strcmp are both non-constant-time, exploitable byte by byte via timing side channels
$known = "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7";
$good = "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7";
$evil = "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb8";
var_dump(hash_equals($known, $good));
var_dump(hash_equals($known, $evil));
// A length mismatch is false immediately (truncated-string attacks get no byte-by-byte leak)
var_dump(hash_equals($known, substr($evil, 0, 10)));
var_dump($known == $good); // Anti-pattern: == is not constant-time
bool(true) bool(false) bool(false) bool(true)
Python v3.15.2
import hmac
# hmac.compare_digest: constant-time comparison (str is ASCII-only, bytes unrestricted) — the standard defense against timing attacks
known = "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7"
good = "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7"
evil = "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb8"
print(hmac.compare_digest(known, good))
print(hmac.compare_digest(known, evil))
# Length mismatch: returns False (no exception), also constant-time
print(hmac.compare_digest(known, evil[:10]))
# == is not constant-time — never use it in security contexts
print(known == good)
True False False True
Rust v1.99.1
// Constant-time comparison idiom: accumulate XOR differences, then decide — never return early (early returns leak comparison progress)
fn ct_equal(a: &[u8], b: &[u8]) -> bool {
let mut diff = (a.len() ^ b.len()) as u8; // Length differences join the accumulation too
let n = a.len().min(b.len());
for i in 0..n {
diff |= a[i] ^ b[i];
}
diff == 0
}
fn main() {
let known = b"10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7";
let good = b"10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7";
let evil = b"10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb8";
println!("{}", ct_equal(known, good));
println!("{}", ct_equal(known, evil));
println!("{}", ct_equal(known, &evil[..10])); // Length mismatch → false
println!("{}", known == good); // == is not constant-time — never use it in security contexts
}
true false false true
TypeScript v26.13.1
import { timingSafeEqual } from "node:crypto";
// timingSafeEqual: constant-time comparison — but a length mismatch throws RangeError outright (the only one of the ten languages that throws)
const known = Buffer.from("10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7", "hex");
const good = Buffer.from("10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7", "hex");
const evil = Buffer.from("10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb8", "hex");
console.log(timingSafeEqual(known, good));
console.log(timingSafeEqual(known, evil));
try {
timingSafeEqual(known, evil.subarray(0, 10));
} catch {
console.log("length mismatch -> throws");
}
console.log(known.equals(good)); // equals is an ordinary comparison (not constant-time) — never use it in security contexts
true false length mismatch -> throws true
Language differences
C: no standard-library constant-time compare — the hand-written idiom: accumulate XOR differences (diff |= a[i] ^ b[i]) through the whole loop, fold the length difference in, never return early; OpenSSL's CRYPTO_memcmp is the production pick.
C++: same hand-written idiom (example); real work uses OpenSSL CRYPTO_memcmp or libsodium sodium_memcmp.
C#: CryptographicOperations.FixedTimeEquals (.NET Core 2.1+) — span comparison; mismatched lengths return false rather than throwing.
Go: crypto/subtle.ConstantTimeCompare — returns 1/0 (also 0 on length mismatch), not a bool, so convert it yourself; hmac.Equal is the constant-time wrapper.
Java: MessageDigest.isEqual — before JDK 6u17 it was an early-return, non-constant-time implementation (a textbook historical vulnerability); fixed since; mismatched lengths return false.
JavaScript: crypto.timingSafeEqual — constant-time but throws RangeError on length mismatch (the only one of the ten to throw); takes Buffer/TypedArray only.
PHP: hash_equals is the mandatory way to compare MACs/hashes; mismatched lengths return false immediately; == and strcmp are not constant-time — timing side channels can brute-force byte by byte; put the known-good value in $known_string (the first argument).
Python: hmac.compare_digest — str must be ASCII, bytes unrestricted; mismatched lengths return False without throwing.
Rust: nothing in std — hand-write the idiom (example); real work uses the subtle crate's ConstantTimeEq or constant_time_eq.
TypeScript: same as JavaScript (Node crypto.timingSafeEqual + Buffer).