[hashes] Use `fixed_time_eq` for `Hmac::eq`

When someone is checking if an `Hmac` is equal to some other
`Hmac`, its fairly common for them to be doing a
constant-time-ness-sensitive operation. Thus, here we default to
our existing `fixed_time_eq` method for `PartialEq` on `Hamc`,
rather than the naive Rust slice comparison.

While we should consider doing the same for all hash types, we do
not yet do so here.
This commit is contained in:
Matt Corallo 2025-03-28 13:42:46 +00:00
parent 7ac7273013
commit 2d9e240fb6
1 changed files with 10 additions and 1 deletions

View File

@ -15,8 +15,9 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::{Hash, HashEngine};
/// A hash computed from a RFC 2104 HMAC. Parameterized by the underlying hash function.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(Copy, Clone, PartialOrd, Ord, Hash)]
#[repr(transparent)]
#[allow(clippy::derived_hash_with_manual_eq)]
pub struct Hmac<T: Hash>(T);
impl<T: Hash + str::FromStr> str::FromStr for Hmac<T> {
@ -24,6 +25,14 @@ impl<T: Hash + str::FromStr> str::FromStr for Hmac<T> {
fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Hmac(str::FromStr::from_str(s)?)) }
}
impl<T: Hash> PartialEq for Hmac<T> {
fn eq(&self, other: &Self) -> bool {
crate::cmp::fixed_time_eq(self.as_ref(), other.as_ref())
}
}
impl<T: Hash> Eq for Hmac<T> {}
/// Pair of underlying hash engines, used for the inner and outer hash of HMAC.
#[derive(Debug, Clone)]
pub struct HmacEngine<T: HashEngine> {