secure_compare

Function secure_compare 

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

Compares two byte slices in constant time.

This function performs a timing-safe comparison of two byte slices, preventing timing attacks that could leak information about the contents of secret data.

§Security

This function is designed to take the same amount of time regardless of where the first difference occurs. This prevents attackers from using timing measurements to guess secret values byte-by-byte.

Use this function when comparing:

  • Authentication cookies
  • HMAC values
  • Password hashes
  • Any security-sensitive data

§Arguments

  • a - First byte slice
  • b - Second byte slice

§Returns

true if the slices are equal, false otherwise.

§Implementation

The comparison XORs all bytes and accumulates differences, ensuring all bytes are always compared regardless of early mismatches.

§Example

use stem_rs::util::secure_compare;

let secret = b"my_secret_cookie";
let attempt = b"my_secret_cookie";
let wrong = b"wrong_cookie_val";

assert!(secure_compare(secret, attempt));
assert!(!secure_compare(secret, wrong));

// Different lengths always return false
assert!(!secure_compare(b"short", b"longer"));

§This Compiles But Is Wrong

// DON'T use regular equality for secrets - it's vulnerable to timing attacks
let secret = b"authentication_cookie";
let attempt = b"authentication_cookie";

// This is INSECURE - timing varies based on first differing byte
// if secret == attempt { ... }

// Use secure_compare instead
use stem_rs::util::secure_compare;
if secure_compare(secret, attempt) {
    // Safe comparison
}