From d7df5b4da99c5c20e8b21cad71224a80eb8cceb7 Mon Sep 17 00:00:00 2001 From: pinkforest <36498018+pinkforest@users.noreply.github.com> Date: Sun, 12 Mar 2023 16:09:09 +1100 Subject: [PATCH] Add getrandom to bring convenience random init functions This is a reroll of #103 to correct branch Co-authored-by: Ciprian Dorin Craciun --- Cargo.toml | 1 + src/x25519.rs | 16 ++++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 5441ff1..45d491b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,6 +50,7 @@ harness = false [features] default = ["alloc", "precomputed-tables", "zeroize"] +getrandom = ["rand_core/getrandom"] zeroize = ["dep:zeroize", "curve25519-dalek/zeroize"] serde = ["dep:serde", "curve25519-dalek/serde"] alloc = ["curve25519-dalek/alloc", "serde?/alloc", "zeroize?/alloc"] diff --git a/src/x25519.rs b/src/x25519.rs index 442f17d..a396fea 100644 --- a/src/x25519.rs +++ b/src/x25519.rs @@ -84,6 +84,11 @@ impl EphemeralSecret { EphemeralSecret(Scalar::from_bits_clamped(bytes)) } + /// Generate an x25519 [`EphemeralSecret`] key using [`rand_core::OsRng`]. + #[cfg(feature = "getrandom")] + pub fn random() -> Self { + Self::new(&mut rand_core::OsRng) + } } impl<'a> From<&'a EphemeralSecret> for PublicKey { @@ -133,6 +138,11 @@ impl ReusableSecret { ReusableSecret(Scalar::from_bits_clamped(bytes)) } + /// Generate a non-serializeable x25519 [`ReuseableSecret`] key using [`rand_core::OsRng`]. + #[cfg(feature = "getrandom")] + pub fn random() -> Self { + Self::new(&mut rand_core::OsRng) + } } #[cfg(feature = "reusable_secrets")] @@ -185,6 +195,12 @@ impl StaticSecret { pub fn to_bytes(&self) -> [u8; 32] { self.0.to_bytes() } + + /// Generate an x25519 key key using [`rand_core::OsRng`]. + #[cfg(feature = "getrandom")] + pub fn random() -> Self { + Self::new(&mut rand_core::OsRng) + } } impl From<[u8; 32]> for StaticSecret {