Skip to main content

pwr_rs/config/
deterministic_random.rs

1use sha2::{Sha256, Digest};
2use std::io::{self, Read};
3
4pub struct DeterministicSecureRandom {
5    digest: Sha256,
6    seed: Vec<u8>,
7    counter: u32,
8}
9
10impl DeterministicSecureRandom {
11    pub fn new(seed: &[u8]) -> Self {
12        Self {
13            digest: Sha256::new(),
14            seed: seed.to_vec(),
15            counter: 0,
16        }
17    }
18
19    pub fn next_bytes(&mut self, bytes: &mut [u8]) {
20        let mut index = 0;
21        while index < bytes.len() {
22            let mut digest = self.digest.clone();
23            digest.update(&self.seed);
24            digest.update(&self.counter.to_be_bytes());
25            let hash = digest.finalize();
26
27            let to_copy = std::cmp::min(hash.len(), bytes.len() - index);
28            bytes[index..index + to_copy].copy_from_slice(&hash[..to_copy]);
29            index += to_copy;
30            self.counter += 1;
31        }
32    }
33}
34
35impl Read for DeterministicSecureRandom {
36    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
37        self.next_bytes(buf);
38        Ok(buf.len())
39    }
40}