Skip to main content

zwave_security/
drbg.rs

1//! AES-128 CTR_DRBG without a derivation function (NIST SP 800-90A Rev. 1,
2//! section 10.2.1), the generator S2 uses for SPAN nonces.
3//!
4//! Both ends of a SPAN seed one of these with the same mixed entropy input
5//! and personalization string and then draw nonces in lockstep, so it must be
6//! bit-exact; it is tested against NIST's CAVP vectors. The AES block
7//! function is the `aes` crate's.
8
9use crate::crypto::{aes128_ecb, increment};
10
11/// Seed length: key length plus block length.
12pub const SEED_LEN: usize = 32;
13
14/// AES-128 CTR_DRBG state (no derivation function, no prediction resistance).
15#[derive(Clone, zeroize::Zeroize, zeroize::ZeroizeOnDrop)]
16pub struct CtrDrbg {
17    key: [u8; 16],
18    v: [u8; 16],
19}
20
21impl std::fmt::Debug for CtrDrbg {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        f.write_str("CtrDrbg(..)")
24    }
25}
26
27impl CtrDrbg {
28    /// Instantiates from 32 bytes of entropy and an optional personalization
29    /// string of at most 32 bytes (shorter strings are zero padded).
30    pub fn new(entropy: &[u8; SEED_LEN], personalization: &[u8]) -> Self {
31        assert!(
32            personalization.len() <= SEED_LEN,
33            "personalization too long"
34        );
35        let mut seed = *entropy;
36        for (s, p) in seed.iter_mut().zip(personalization) {
37            *s ^= p;
38        }
39        let mut d = CtrDrbg {
40            key: [0; 16],
41            v: [0; 16],
42        };
43        d.update(Some(&seed));
44        d
45    }
46
47    fn update(&mut self, provided: Option<&[u8; SEED_LEN]>) {
48        let mut temp = [0u8; SEED_LEN];
49        for chunk in temp.chunks_mut(16) {
50            increment(&mut self.v);
51            chunk.copy_from_slice(&aes128_ecb(&self.key, &self.v));
52        }
53        if let Some(p) = provided {
54            for (t, p) in temp.iter_mut().zip(p) {
55                *t ^= p;
56            }
57        }
58        self.key.copy_from_slice(&temp[..16]);
59        self.v.copy_from_slice(&temp[16..]);
60    }
61
62    /// Reseeds with 32 bytes of new entropy and optional additional input.
63    pub fn reseed(&mut self, entropy: &[u8; SEED_LEN], additional: &[u8]) {
64        assert!(additional.len() <= SEED_LEN, "additional input too long");
65        let mut seed = *entropy;
66        for (s, a) in seed.iter_mut().zip(additional) {
67            *s ^= a;
68        }
69        self.update(Some(&seed));
70    }
71
72    /// Fills `out` with output and advances the state (no additional input).
73    pub fn generate(&mut self, out: &mut [u8]) {
74        self.generate_with(out, &[]);
75    }
76
77    /// Fills `out` with output, mixing in up to 32 bytes of additional input.
78    pub fn generate_with(&mut self, out: &mut [u8], additional: &[u8]) {
79        assert!(additional.len() <= SEED_LEN, "additional input too long");
80        let add = if additional.is_empty() {
81            None
82        } else {
83            let mut a = [0u8; SEED_LEN];
84            a[..additional.len()].copy_from_slice(additional);
85            self.update(Some(&a));
86            Some(a)
87        };
88        for chunk in out.chunks_mut(16) {
89            increment(&mut self.v);
90            let block = aes128_ecb(&self.key, &self.v);
91            chunk.copy_from_slice(&block[..chunk.len()]);
92        }
93        self.update(add.as_ref());
94    }
95
96    /// Draws one 16-byte block and returns its first 13 bytes: an S2 nonce.
97    pub fn next_nonce(&mut self) -> [u8; 13] {
98        let mut block = [0u8; 16];
99        self.generate(&mut block);
100        let mut n = [0u8; 13];
101        n.copy_from_slice(&block[..13]);
102        n
103    }
104}