From 4c259275d672f050f009ccaf7d5b1a7549e65af2 Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Wed, 5 Nov 2025 08:24:43 -0700 Subject: [PATCH] password-hash: restore/fix `getrandom` feature It seems it was never properly converted to `os_rng`. Adds (back) a `getrandom` feature and a way to generate `SaltString`s using the system random number generator. --- Cargo.lock | 1 + password-hash/Cargo.toml | 3 ++- password-hash/src/salt.rs | 12 +++++++++--- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e51079b1b..8a694c385 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -358,6 +358,7 @@ name = "password-hash" version = "0.6.0-rc.1" dependencies = [ "base64ct", + "getrandom", "rand_core", "subtle", ] diff --git a/password-hash/Cargo.toml b/password-hash/Cargo.toml index d1720c3b3..604c1f04b 100644 --- a/password-hash/Cargo.toml +++ b/password-hash/Cargo.toml @@ -21,12 +21,13 @@ base64ct = "1.7" subtle = { version = "2", default-features = false } # optional dependencies +getrandom = { version = "0.3", optional = true, default-features = false } rand_core = { version = "0.10.0-rc-2", optional = true, default-features = false } [features] default = ["rand_core"] +getrandom = ["dep:getrandom"] rand_core = ["dep:rand_core"] -#os_rng = ["rand_core", "rand_core/os_rng"] alloc = ["base64ct/alloc"] [package.metadata.docs.rs] diff --git a/password-hash/src/salt.rs b/password-hash/src/salt.rs index 2d1975407..fca6734dd 100644 --- a/password-hash/src/salt.rs +++ b/password-hash/src/salt.rs @@ -186,12 +186,18 @@ pub struct SaltString { #[allow(clippy::len_without_is_empty)] impl SaltString { + /// Generate a random B64-encoded [`SaltString`]. + #[cfg(feature = "getrandom")] + pub fn generate() -> Self { + let mut bytes = [0u8; Salt::RECOMMENDED_LENGTH]; + getrandom::fill(&mut bytes).expect("RNG failure"); + Self::encode_b64(&bytes).expect(INVARIANT_VIOLATED_MSG) + } + /// Generate a random B64-encoded [`SaltString`] from [`CryptoRng`]. #[cfg(feature = "rand_core")] pub fn from_rng(rng: &mut R) -> Self { - let mut bytes = [0u8; Salt::RECOMMENDED_LENGTH]; - rng.fill_bytes(&mut bytes); - Self::encode_b64(&bytes).expect(INVARIANT_VIOLATED_MSG) + Self::try_from_rng(rng).expect("RNG failure") } /// Generate a random B64-encoded [`SaltString`] from [`TryCryptoRng`].