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.
Code
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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.