Skip to main content

zaun_community_protocol/crypto/
secret.rs

1//! The composite private key (specification §3.2).
2
3use std::fmt;
4use std::sync::OnceLock;
5
6use ml_dsa::{ExpandedSigningKey, MlDsa65, Seed};
7use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
8
9use super::composite::assemble_public_key;
10use crate::ids::{RngError, fill_random};
11use crate::keys::PublicKey;
12
13/// Length of [`SecretKey`]: `mldsaSeed` (32) ‖ `edSK` (32).
14pub const SECRET_KEY_LEN: usize = 64;
15
16/// A suite-1 composite private key: `mldsaSeed` (FIPS 204 ξ, 32 B) ‖ `edSK` (32 B).
17///
18/// Never on the wire. `Debug` is redacted and the bytes are zeroized on drop. Its component
19/// keys are used only inside this composite (RFC 10073 §3.1).
20///
21/// The ML-DSA-65 expanded signing key is derived from the seed once, on first use, and kept
22/// with the key (it is zeroized on drop too): deriving it is about a fifth of the cost of a
23/// signature, and a host signs a session proof for every `session.hello`.
24#[derive(Clone)]
25pub struct SecretKey {
26    bytes: [u8; SECRET_KEY_LEN],
27    expanded: OnceLock<Box<ExpandedSigningKey<MlDsa65>>>,
28}
29
30impl Zeroize for SecretKey {
31    fn zeroize(&mut self) {
32        self.bytes.zeroize();
33        // `ExpandedSigningKey` zeroizes itself when dropped.
34        drop(self.expanded.take());
35    }
36}
37
38impl Drop for SecretKey {
39    fn drop(&mut self) {
40        self.zeroize();
41    }
42}
43
44impl ZeroizeOnDrop for SecretKey {}
45
46impl SecretKey {
47    /// A fresh key from the OS CSPRNG.
48    ///
49    /// # Errors
50    /// [`RngError`] when `getrandom` fails.
51    pub fn generate() -> Result<Self, RngError> {
52        let mut key = Self::from_bytes(&[0u8; SECRET_KEY_LEN]);
53        fill_random(&mut key.bytes)?;
54        Ok(key)
55    }
56
57    /// Wraps the 64-byte encoding. The caller zeroizes its own copy.
58    #[must_use]
59    pub fn from_bytes(bytes: &[u8; SECRET_KEY_LEN]) -> Self {
60        Self {
61            bytes: *bytes,
62            expanded: OnceLock::new(),
63        }
64    }
65
66    /// The 64-byte encoding, for sealed storage only.
67    #[must_use]
68    pub const fn expose_secret(&self) -> &[u8; SECRET_KEY_LEN] {
69        &self.bytes
70    }
71
72    /// The ML-DSA-65 expanded signing key, derived from `mldsaSeed` on first use (zeroized
73    /// on drop).
74    pub(super) fn mldsa(&self) -> &ExpandedSigningKey<MlDsa65> {
75        self.expanded.get_or_init(|| {
76            let mut seed = Zeroizing::new([0u8; 32]);
77            seed.copy_from_slice(&self.bytes[..32]);
78            let seed = Zeroizing::new(Seed::from(*seed));
79            Box::new(ExpandedSigningKey::from_seed(&seed))
80        })
81    }
82
83    /// The Ed25519 signing key (zeroized on drop).
84    pub(super) fn ed25519(&self) -> ed25519_dalek::SigningKey {
85        let mut sk = Zeroizing::new([0u8; 32]);
86        sk.copy_from_slice(&self.bytes[32..]);
87        ed25519_dalek::SigningKey::from_bytes(&sk)
88    }
89
90    /// The composite public key (§3.4): suite `0x01` ‖ `mldsaPK` ‖ `edPK`.
91    #[must_use]
92    pub fn public_key(&self) -> PublicKey {
93        let mldsa = self.mldsa().verifying_key().encode();
94        let ed = self.ed25519().verifying_key().to_bytes();
95        assemble_public_key(&mldsa, &ed)
96    }
97}
98
99impl fmt::Debug for SecretKey {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        f.write_str("SecretKey(<redacted>)")
102    }
103}