Skip to content

Commit

Permalink
fix: hashing in a timing attack resistant way
Browse files Browse the repository at this point in the history
  • Loading branch information
kate-shine committed Sep 11, 2023
1 parent 89fa227 commit 0106ef8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
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
20 changes: 19 additions & 1 deletion 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 Expand Up @@ -579,7 +597,7 @@ new_secret_type![
/// via the `state` parameter.
///
#[must_use]
#[derive(Clone, Deserialize, Serialize, Hash, PartialEq, Eq)]
#[derive(Clone, Deserialize, Serialize)]
CsrfToken(String)
impl {
///
Expand Down

0 comments on commit 0106ef8

Please sign in to comment.