rs-matter-stack 0.2.0

Utility for configuring and running rs-matter
Documentation
//! A simple adaptor to convert between `rand_core` V0.6 and `rand_core` V0.9
//!
//! A reseeding RNG implementation that wraps an existing RNG and reseeds it after a specified number of generated bytes.
//! Copied over from the `rand` project which recently retired theirs.

pub use rand_chacha::*;
pub use reseeding::ReseedingRng;

use crate::matter::crypto::{CryptoRng, RngCore};

mod reseeding;

/// A simple adaptor to convert between `rand_core` V0.6 and `rand_core` V0.9
pub struct RngAdaptor<T>(T);

impl<T> RngAdaptor<T> {
    /// Create a new `RandAdaptor` instance wrapping the provided RNG.
    pub const fn new(rng: T) -> Self {
        Self(rng)
    }
}

impl<T> rand_core09::RngCore for RngAdaptor<T>
where
    T: RngCore,
{
    fn next_u32(&mut self) -> u32 {
        self.0.next_u32()
    }

    fn next_u64(&mut self) -> u64 {
        self.0.next_u64()
    }

    fn fill_bytes(&mut self, dest: &mut [u8]) {
        self.0.fill_bytes(dest);
    }
}

impl<T> rand_core09::CryptoRng for RngAdaptor<T> where T: RngCore + CryptoRng {}

impl<T> RngCore for RngAdaptor<T>
where
    T: rand_core09::RngCore,
{
    fn next_u32(&mut self) -> u32 {
        self.0.next_u32()
    }

    fn next_u64(&mut self) -> u64 {
        self.0.next_u64()
    }

    fn fill_bytes(&mut self, dest: &mut [u8]) {
        self.0.fill_bytes(dest);
    }

    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core06::Error> {
        self.0.fill_bytes(dest);

        Ok(())
    }
}

impl<T> CryptoRng for RngAdaptor<T> where T: rand_core09::RngCore + rand_core09::CryptoRng {}

/// Create a reseeding CSPRNG using ChaCha12Core as the underlying PRNG.
/// A good default as an argument to the various `rs-matter` crypto backends, especially in baremetal environments.
///
/// # Arguments
/// - `trng`: The true random number generator to use for reseeding.
/// - `reseed_threshold`: The number of bytes to generate before reseeding.
///
/// # Returns
/// An adaptor wrapping the reseeding RNG, or an error if the underlying TRNG fails to initialize.
pub fn reseeding_csprng<T: rand_core09::TryRngCore>(
    trng: T,
    reseed_threshold: u64,
) -> Result<RngAdaptor<ReseedingRng<ChaCha12Core, T>>, T::Error> {
    Ok(RngAdaptor::new(ReseedingRng::new(reseed_threshold, trng)?))
}