Skip to main content

constant_time_eq

Function constant_time_eq 

Source
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool
Expand description

Performs constant-time comparison of two byte slices.

This function compares two byte slices in a way that takes the same amount of time regardless of where (or if) the slices differ. This prevents timing attacks where an attacker can deduce secret values by measuring comparison time.

§Security Properties

  • Constant time: Always iterates through all bytes regardless of mismatches
  • No early return: Uses bitwise OR to accumulate differences
  • Length-safe: Returns false for different lengths (but length itself may leak)

§Timing Attack Prevention

A naive comparison like a == b returns as soon as it finds a difference:

  • "secret" == "aaaaaa" returns immediately (first byte differs)
  • "secret" == "saaaaa" takes slightly longer (second byte differs)
  • "secret" == "seaaaa" takes even longer, etc.

An attacker can exploit this to guess a secret character-by-character. This function prevents that by always examining all bytes.

§Warning: Length Leakage

While the comparison itself is constant-time, this function returns false immediately if the lengths differ. This is intentional for most use cases, but be aware that an attacker may be able to determine the length of secret values. For HMAC comparison, this is typically acceptable since HMACs have fixed, known lengths.

§Example

use fastapi_core::constant_time_eq;

let secret_token = b"supersecrettoken12345";
let user_input = b"supersecrettoken12345";

if constant_time_eq(secret_token, user_input) {
    // Tokens match - grant access
} else {
    // Tokens don't match - deny access
}

§When to Use

Use this function when comparing:

  • Authentication tokens
  • API keys
  • Session IDs
  • HMAC signatures
  • Password hashes (after hashing)
  • Any secret value where timing attacks are a concern