Skip to main content

at_cryptoauth/client/
random.rs

1//! Random number generation
2
3use crate::command;
4use crate::error::{Error, ErrorKind};
5use core::num::NonZeroU32;
6use embassy_sync::blocking_mutex::raw::RawMutex;
7use signature::rand_core;
8
9use super::AtCaClient;
10
11pub struct Random<'a, M: RawMutex, PHY> {
12    pub(crate) atca: &'a AtCaClient<M, PHY>,
13}
14
15impl<'a, M: RawMutex, PHY> Random<'a, M, PHY> {
16    pub fn new(atca: &'a AtCaClient<M, PHY>) -> Self {
17        Self { atca }
18    }
19}
20
21impl<'a, M, PHY> Random<'a, M, PHY>
22where
23    PHY: embedded_hal_async::i2c::I2c,
24    M: RawMutex,
25{
26    pub async fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
27        for c in dest.chunks_mut(32) {
28            let mut inner = self.atca.inner.lock().await;
29
30            let packet = command::Random::new(inner.packet_builder()).random()?;
31            let resp = inner.execute(packet).await?;
32            let len = c.len().min(resp.as_ref().len());
33            c[..len].copy_from_slice(&resp.as_ref()[..len]);
34        }
35        Ok(())
36    }
37}
38
39impl<'a, M, PHY> Random<'a, M, PHY>
40where
41    PHY: embedded_hal::i2c::I2c,
42    M: RawMutex,
43{
44    pub fn try_fill_bytes_blocking(&mut self, dest: &mut [u8]) -> Result<(), Error> {
45        let mut inner = self
46            .atca
47            .inner
48            .try_lock()
49            .map_err(|_| ErrorKind::MutexLocked)?;
50
51        for c in dest.chunks_mut(32) {
52            let packet = command::Random::new(inner.packet_builder()).random()?;
53            let resp = inner.execute_blocking(packet)?;
54            let len = c.len().min(resp.as_ref().len());
55            c[..len].copy_from_slice(&resp.as_ref()[..len]);
56        }
57        Ok(())
58    }
59}
60
61impl<'a, M, PHY> rand_core::RngCore for Random<'a, M, PHY>
62where
63    PHY: embedded_hal::i2c::I2c,
64    M: RawMutex,
65{
66    fn next_u32(&mut self) -> u32 {
67        rand_core::impls::next_u32_via_fill(self)
68    }
69
70    fn next_u64(&mut self) -> u64 {
71        rand_core::impls::next_u64_via_fill(self)
72    }
73
74    fn fill_bytes(&mut self, dest: &mut [u8]) {
75        rand_core::RngCore::try_fill_bytes(self, dest).unwrap()
76    }
77
78    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
79        self.try_fill_bytes_blocking(dest)
80            .map_err(|e| NonZeroU32::new(e.code()).unwrap())?;
81
82        Ok(())
83    }
84}
85
86impl<'a, M, PHY> rand_core::CryptoRng for Random<'a, M, PHY>
87where
88    PHY: embedded_hal::i2c::I2c,
89    M: RawMutex,
90{
91}