From d93c4fc4c864329d936aff321ce1b419092e744b Mon Sep 17 00:00:00 2001 From: Rob Young Date: Sun, 26 Sep 2021 11:51:01 +0100 Subject: [PATCH] Implement RngCore for RingOscillator (#135) Implement rand_core::RngCore for RingOscillator from the get_random_bit function. This is not suitable for security purposes so rand_core::CryptoRng has not been implemented. --- CHANGELOG.md | 3 +++ rp2040-hal/Cargo.toml | 1 + rp2040-hal/src/rosc.rs | 25 +++++++++++++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 04cc8f1..e254d28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- implement `rng_core::RngCore` for `RingOscillator` + ## [0.3.0] - 2021-09-20 ### Added diff --git a/rp2040-hal/Cargo.toml b/rp2040-hal/Cargo.toml index 71a4360..6598c61 100644 --- a/rp2040-hal/Cargo.toml +++ b/rp2040-hal/Cargo.toml @@ -21,6 +21,7 @@ pio = { git = "https://github.com/rp-rs/pio-rs.git", branch = "main" } usb-device = "0.2.8" vcell = "0.1" void = { version = "1.0.2", default-features = false } +rand_core = "0.6.3" [dev-dependencies] cortex-m-rt = "0.7" diff --git a/rp2040-hal/src/rosc.rs b/rp2040-hal/src/rosc.rs index 520d0ea..e392056 100644 --- a/rp2040-hal/src/rosc.rs +++ b/rp2040-hal/src/rosc.rs @@ -97,3 +97,28 @@ impl RingOscillator { self.transition(Dormant) } } + +impl rand_core::RngCore for RingOscillator { + fn next_u32(&mut self) -> u32 { + rand_core::impls::next_u32_via_fill(self) + } + + fn next_u64(&mut self) -> u64 { + rand_core::impls::next_u64_via_fill(self) + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + for chunk in dest.iter_mut() { + *chunk = 0_u8; + for _ in 0..8 { + *chunk <<= 1; + *chunk ^= self.get_random_bit() as u8; + } + } + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> { + self.fill_bytes(dest); + Ok(()) + } +}