use subtle::ConstantTimeEq;
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
let len_eq = (a.len() as u64).ct_eq(&(b.len() as u64));
let max_len = a.len().max(b.len());
let mut byte_eq = subtle::Choice::from(1u8);
for i in 0..max_len {
let x = a.get(i).copied().unwrap_or(0);
let y = b.get(i).copied().unwrap_or(0);
byte_eq &= x.ct_eq(&y);
}
(len_eq & byte_eq).unwrap_u8() == 1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn equal_slices_return_true() {
assert!(constant_time_eq(b"hello", b"hello"));
assert!(constant_time_eq(b"", b""));
assert!(constant_time_eq(&[0u8; 32], &[0u8; 32]));
}
#[test]
fn different_slices_return_false() {
assert!(!constant_time_eq(b"hello", b"world"));
assert!(!constant_time_eq(b"hello", b"hellp"));
}
#[test]
fn different_lengths_return_false() {
assert!(!constant_time_eq(b"abc", b"abcd"));
assert!(!constant_time_eq(b"abcd", b"abc"));
assert!(!constant_time_eq(b"", b"a"));
}
#[test]
fn long_inputs_no_panic() {
let a = vec![0u8; 1024];
let b = vec![0u8; 1024];
assert!(constant_time_eq(&a, &b));
let mut c = b.clone();
c[1023] = 1;
assert!(!constant_time_eq(&a, &c));
}
}