rustauth_core/crypto/buffer.rs
1//! Constant-time byte comparison helpers.
2
3/// Compare two byte-like values without early returns based on content.
4pub fn constant_time_equal<A, B>(a: A, b: B) -> bool
5where
6 A: AsRef<[u8]>,
7 B: AsRef<[u8]>,
8{
9 let a = a.as_ref();
10 let b = b.as_ref();
11 let mut diff = a.len() ^ b.len();
12 let length = a.len().max(b.len());
13
14 for index in 0..length {
15 let left = a.get(index).copied().unwrap_or(0);
16 let right = b.get(index).copied().unwrap_or(0);
17 diff |= usize::from(left ^ right);
18 }
19
20 diff == 0
21}