use subtle::ConstantTimeEq;
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
a.ct_eq(b).into()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_constant_time_eq_equal() {
assert!(constant_time_eq(b"hello", b"hello"));
assert!(constant_time_eq(b"", b""));
assert!(constant_time_eq(&[1, 2, 3], &[1, 2, 3]));
}
#[test]
fn test_constant_time_eq_not_equal() {
assert!(!constant_time_eq(b"hello", b"world"));
assert!(!constant_time_eq(&[1, 2, 3], &[1, 2, 4]));
}
#[test]
fn test_constant_time_eq_different_lengths() {
assert!(!constant_time_eq(b"hello", b"hello!"));
assert!(!constant_time_eq(b"", b"x"));
}
#[test]
fn test_constant_time_eq_first_byte_different() {
assert!(!constant_time_eq(b"abcd", b"xbcd"));
}
#[test]
fn test_constant_time_eq_last_byte_different() {
assert!(!constant_time_eq(b"abcd", b"abcx"));
}
#[test]
fn test_constant_time_eq_middle_byte_different() {
assert!(!constant_time_eq(b"abcd", b"abxd"));
}
}