Implement constant time comparison for SecretKey

The current implementation of `PartialEq` leaks data because it is not
constant time.

Attempt to make the `PartialEq` implementation constant time.
This commit is contained in:
Tobin C. Harding 2022-11-22 10:09:59 +11:00
parent 19039d9281
commit 7cf3c6c8a4
1 changed files with 4 additions and 1 deletions

View File

@ -61,9 +61,12 @@ pub struct SecretKey([u8; constants::SECRET_KEY_SIZE]);
impl_display_secret!(SecretKey); impl_display_secret!(SecretKey);
impl PartialEq for SecretKey { impl PartialEq for SecretKey {
/// This implementation is designed to be constant time to help prevent side channel attacks.
#[inline] #[inline]
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self[..] == other[..] let accum = self.0.iter().zip(&other.0)
.fold(0, |accum, (a, b)| accum | a ^ b);
unsafe { core::ptr::read_volatile(&accum) == 0 }
} }
} }