Constant-Time Byte Comparison

Compare secrets without early exit so timing does not leak the matching prefix, and keep the result observable with black_box.

RustSecurity Boundaries

Code

rustsnippet
23 lines
use std::hint::black_box;

fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
    if left.len() != right.len() {
        return false;
    }
    let mut difference = 0u8;
    for (a, b) in left.iter().zip(right.iter()) {
        difference |= a ^ b;
    }
    black_box(difference) == 0
}

fn compare_tokens(expected: &str, provided: &str) -> bool {
    constant_time_eq(expected.as_bytes(), provided.as_bytes())
}

fn main() {
    println!("equal: {}", compare_tokens("token-abc", "token-abc"));
    println!("different: {}", compare_tokens("token-abc", "token-abd"));
    println!("length mismatch: {}", compare_tokens("token-abc", "token"));
    println!("empty: {}", compare_tokens("", ""));
}

What the code does

The snippet is organized around the functions constant_time_eq, compare_tokens and main.

Repetition is confined to for (a, b) in left.iter().zip(right.iter()) — the rest of the file is straight-line.

Applying it

The main signature reads fn constant_time_eq(left: &[u8], right: &[u8]) -> bool

The demo output is labeled (equal:, different:, length mismatch:), so every printed line maps back to its originating operation.

Running the file executes main, which drives compare_tokens in order.

Statements that matter

for (a, b) in left.iter().zip(right.iter()) {
    difference |= a ^ b;
}
fn compare_tokens(expected: &str, provided: &str) -> bool {
    constant_time_eq(expected.as_bytes(), provided.as_bytes())
}

Interactive Tools for This Topic

FAQ

What does Constant-Time Byte Comparison print when run?
Run it as a complete program — the output lines carry labels such as `equal:`, `different:`, `length mismatch:`.