From 7cf3c6c8a4ba76c1a1165ff9f102d10f4af9a290 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Tue, 22 Nov 2022 10:09:59 +1100 Subject: [PATCH] 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. --- src/key.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/key.rs b/src/key.rs index 9bbf8c7..3979be6 100644 --- a/src/key.rs +++ b/src/key.rs @@ -61,9 +61,12 @@ pub struct SecretKey([u8; constants::SECRET_KEY_SIZE]); impl_display_secret!(SecretKey); impl PartialEq for SecretKey { + /// This implementation is designed to be constant time to help prevent side channel attacks. #[inline] 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 } } }