Skip to content

Commit

Permalink
Add timing-resistant-secret-traits feature for PartialEq/Hash (#232)
Browse files Browse the repository at this point in the history
Derived implementations of `PartialEq` and `Hash` are susceptible to
timing side channels that make them unsuitable for secret types. This
change introduces timing-safe implementations of `PartialEq` and `Hash`
to all secret types that compare/hash, respectively, the SHA-256 hash
of the secret rather than the secret itself. Because these
implementations are significantly more computationally expensive than
ordinary `PartialEq` and `Hash` implementations, they're behind a
non-default `timing-resistant-secret-traits` feature flag.
  • Loading branch information
kate-shine authored Sep 11, 2023
1 parent 8e66503 commit ed63126
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ default = ["reqwest", "rustls-tls"]
pkce-plain = []
native-tls = ["reqwest/native-tls"]
rustls-tls = ["reqwest/rustls-tls"]
timing-resistant-secret-traits = []

[dependencies]
base64 = "0.13"
Expand Down
18 changes: 18 additions & 0 deletions src/types.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use std::convert::Into;
use std::fmt::Error as FormatterError;
use std::fmt::{Debug, Formatter};
#[cfg(feature = "timing-resistant-secret-traits")]
use std::hash::{Hash, Hasher};
use std::ops::Deref;

use rand::{thread_rng, Rng};
Expand Down Expand Up @@ -148,6 +150,7 @@ macro_rules! new_secret_type {
$(
#[$attr]
)*
#[cfg_attr(feature = "timing-resistant-secret-traits", derive(Eq))]
pub struct $name($type);
impl $name {
$($item)*
Expand All @@ -170,6 +173,21 @@ macro_rules! new_secret_type {
write!(f, concat!(stringify!($name), "([redacted])"))
}
}

#[cfg(feature = "timing-resistant-secret-traits")]
impl PartialEq for $name {
fn eq(&self, other: &Self) -> bool {
Sha256::digest(&self.0) == Sha256::digest(&other.0)
}
}

#[cfg(feature = "timing-resistant-secret-traits")]
impl Hash for $name {
fn hash<H: Hasher>(&self, state: &mut H) {
Sha256::digest(&self.0).hash(state)
}
}

};
}

Expand Down

0 comments on commit ed63126

Please sign in to comment.