Skip to main content

bitwarden_crypto_primitives/rustcrypto/
ml_dsa_44.rs

1use ml_dsa::{
2    B32, EncodedVerifyingKey, ExpandedSigningKey, MlDsa44, Signature, signature::Verifier,
3};
4use zeroize::Zeroizing;
5
6use super::random::fill_bytes;
7use crate::{Error, ml_dsa_44::SEED_LEN, random::SystemRng};
8
9/// Seed and expanded key. The seed is kept because it is the serialized form.
10#[derive(Clone)]
11pub(crate) struct SigningKey {
12    seed: Zeroizing<[u8; SEED_LEN]>,
13    key: Box<ExpandedSigningKey<MlDsa44>>,
14}
15
16// Both fields wipe themselves on drop.
17impl zeroize::ZeroizeOnDrop for SigningKey {}
18const _: fn() = || {
19    fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
20    assert_zeroize_on_drop::<ExpandedSigningKey<MlDsa44>>();
21};
22
23impl SigningKey {
24    pub(crate) fn generate() -> Self {
25        let mut seed = Zeroizing::new([0u8; 32]);
26        fill_bytes(seed.as_mut_slice());
27        Self::from_seed(&seed)
28    }
29
30    pub(crate) fn from_seed(seed: &[u8; SEED_LEN]) -> Self {
31        // Fill the array in place so no unzeroized copy of the seed is left on the stack.
32        let mut b32 = Zeroizing::new(B32::default());
33        b32.copy_from_slice(seed);
34        Self {
35            seed: Zeroizing::new(*seed),
36            key: Box::new(ExpandedSigningKey::<MlDsa44>::from_seed(&b32)),
37        }
38    }
39
40    pub(crate) fn seed(&self) -> Zeroizing<[u8; SEED_LEN]> {
41        self.seed.clone()
42    }
43
44    pub(crate) fn verifying_key(&self) -> VerifyingKey {
45        VerifyingKey(Box::new(self.key.verifying_key()))
46    }
47
48    /// Hedged signing with an empty context.
49    pub(crate) fn sign(&self, msg: &[u8]) -> Vec<u8> {
50        self.key
51            .sign_randomized(msg, &[], &mut SystemRng)
52            .expect("Empty ML-DSA context must be accepted")
53            .encode()
54            .to_vec()
55    }
56}
57
58#[derive(Clone)]
59pub(crate) struct VerifyingKey(Box<ml_dsa::VerifyingKey<MlDsa44>>);
60
61/// Public data: compare encodings.
62impl PartialEq for VerifyingKey {
63    fn eq(&self, other: &Self) -> bool {
64        self.0.encode() == other.0.encode()
65    }
66}
67
68impl Eq for VerifyingKey {}
69
70impl VerifyingKey {
71    pub(crate) fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
72        let encoded =
73            EncodedVerifyingKey::<MlDsa44>::try_from(bytes).map_err(|_| Error::InvalidKey)?;
74        Ok(Self(Box::new(ml_dsa::VerifyingKey::<MlDsa44>::decode(
75            &encoded,
76        ))))
77    }
78
79    pub(crate) fn to_bytes(&self) -> Vec<u8> {
80        self.0.encode().to_vec()
81    }
82
83    pub(crate) fn verify(&self, msg: &[u8], sig: &[u8]) -> Result<(), Error> {
84        let sig = Signature::<MlDsa44>::try_from(sig).map_err(|_| Error::InvalidSignature)?;
85        self.0
86            .verify(msg, &sig)
87            .map_err(|_| Error::InvalidSignature)
88    }
89}