From 07ee6fafb320a651992078094fbd353b0039c7fa Mon Sep 17 00:00:00 2001 From: Yuki Kishimoto Date: Fri, 7 Aug 2026 12:03:07 +0200 Subject: [PATCH] nostr: require `CryptoRng` for secret key generation Closes https://github.com/nostrdevkit/nostr/issues/1429 Signed-off-by: Yuki Kishimoto --- nostr/CHANGELOG.md | 4 ++++ nostr/examples/embedded/src/main.rs | 4 +++- nostr/src/key/mod.rs | 2 +- nostr/src/key/secret_key.rs | 8 ++++---- 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/nostr/CHANGELOG.md b/nostr/CHANGELOG.md index 5d7ada8a9..8b95e7a6f 100644 --- a/nostr/CHANGELOG.md +++ b/nostr/CHANGELOG.md @@ -29,6 +29,10 @@ ## Unreleased +### Breaking changes + +- Require `CryptoRng` trait for secret key generation (https://github.com/nostrdevkit/nostr/pull/1437) + ### Fixed - The `Display` implementations of `NostrConnectMessage` redact the sensitive data (https://github.com/nostrdevkit/nostr/pull/1432) diff --git a/nostr/examples/embedded/src/main.rs b/nostr/examples/embedded/src/main.rs index 1d271665e..a1cfc244a 100644 --- a/nostr/examples/embedded/src/main.rs +++ b/nostr/examples/embedded/src/main.rs @@ -14,7 +14,7 @@ use core::panic::PanicInfo; use alloc_cortex_m::CortexMHeap; use cortex_m_rt::entry; use cortex_m_semihosting::{debug, hprintln}; -use rand::TryRng; +use rand::{TryRng, TryCryptoRng}; use secp256k1::Secp256k1; use nostr::key::{Keys, SecretKey}; use nostr::nips::nip19::{FromBech32, ToBech32}; @@ -47,6 +47,8 @@ impl TryRng for FakeRng { } } +impl TryCryptoRng for FakeRng {} + #[entry] fn main() -> ! { diff --git a/nostr/src/key/mod.rs b/nostr/src/key/mod.rs index fa020a70f..cd26fe392 100644 --- a/nostr/src/key/mod.rs +++ b/nostr/src/key/mod.rs @@ -154,7 +154,7 @@ impl Keys { pub fn generate_with_rng(secp: &Secp256k1, rng: &mut R) -> Self where C: Signing, - R: Rng, + R: Rng + CryptoRng, { let secret_key: SecretKey = SecretKey::generate_with_rng(rng); Self::new_with_ctx(secp, secret_key) diff --git a/nostr/src/key/secret_key.rs b/nostr/src/key/secret_key.rs index d52e2a63f..daa37c4f3 100644 --- a/nostr/src/key/secret_key.rs +++ b/nostr/src/key/secret_key.rs @@ -8,12 +8,12 @@ use alloc::string::String; use core::ops::{Deref, DerefMut}; use core::str::FromStr; -#[cfg(feature = "rand")] -use rand::Rng; #[cfg(all(feature = "std", feature = "os-rng"))] use rand::rand_core::UnwrapErr; #[cfg(all(feature = "std", feature = "os-rng"))] use rand::rngs::SysRng; +#[cfg(feature = "rand")] +use rand::{CryptoRng, Rng}; use serde::{Deserialize, Deserializer}; use crate::error::{Error, ErrorKind}; @@ -99,12 +99,12 @@ impl SecretKey { #[cfg(feature = "rand")] pub fn generate_with_rng(rng: &mut R) -> Self where - R: Rng, + R: Rng + CryptoRng, { let mut data: [u8; Self::LEN] = util::random_32_bytes(rng); loop { - match secp256k1::SecretKey::from_slice(&data) { + match secp256k1::SecretKey::from_byte_array(&data) { Ok(secret_key) => return Self { inner: secret_key }, Err(_) => data = util::random_32_bytes(rng), }