Skip to main content

weirdnet_keys/
key.rs

1//! 256-bit keys and randomness (the operating system's generator).
2use crate::error::{KeysError, Result};
3use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
4
5/// A 256-bit secret key, wiped on drop and never printed.
6#[derive(Clone, Zeroize, ZeroizeOnDrop, PartialEq, Eq)]
7pub struct Key32(pub [u8; 32]);
8
9impl std::fmt::Debug for Key32 {
10    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11        f.write_str("Key32(<redacted>)")
12    }
13}
14
15impl Key32 {
16    pub fn random() -> Result<Self> {
17        let mut k = Key32([0u8; 32]);
18        getrandom::getrandom(&mut k.0).map_err(|e| KeysError::crypto(e.to_string()))?;
19        Ok(k)
20    }
21    pub fn from_slice(b: &[u8]) -> Result<Self> {
22        if b.len() != 32 {
23            return Err(KeysError::crypto("key must be 32 bytes"));
24        }
25        let mut k = Key32([0u8; 32]);
26        k.0.copy_from_slice(b);
27        Ok(k)
28    }
29    pub fn hex(&self) -> Zeroizing<String> {
30        Zeroizing::new(hex::encode(self.0))
31    }
32    pub fn from_hex(s: &str) -> Result<Self> {
33        let b = Zeroizing::new(hex::decode(s.trim()).map_err(|e| KeysError::crypto(format!("bad key hex: {e}")))?);
34        Self::from_slice(&b)
35    }
36}
37
38/// `N` random bytes from the operating system.
39pub fn random_bytes<const N: usize>() -> Result<[u8; N]> {
40    let mut b = [0u8; N];
41    getrandom::getrandom(&mut b).map_err(|e| KeysError::crypto(e.to_string()))?;
42    Ok(b)
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn keys_are_random_redacted_and_sized() {
51        let (a, b) = (Key32::random().unwrap(), Key32::random().unwrap());
52        assert_ne!(a, b);
53        assert_eq!(format!("{a:?}"), "Key32(<redacted>)");
54        assert_eq!(Key32::from_hex(&a.hex()).unwrap(), a);
55        assert!(Key32::from_slice(&[0u8; 31]).is_err());
56        assert!(Key32::from_hex("zz").is_err());
57    }
58}