Skip to main content

ssh_key/composite/mldsa87_p384/
keys.rs

1//! Keys for the ML-DSA-87 and ECDSA P-384 composite signature algorithm.
2
3use crate::{
4    Algorithm, Error, Result,
5    composite::{PublicKeyBytes, derive_public_key},
6};
7use cipher::cipher::common::Generate;
8use core::fmt;
9use ctutils::{Choice, CtEq};
10use encoding::{CheckedSum, Decode, Decoder, Encode, MpintRef, Reader, Writer};
11use ml_dsa::{EncodedVerifyingKey, MlDsa87, Seed};
12use p384::elliptic_curve::sec1::ToSec1Point;
13use rand_core::CryptoRng;
14use signature::KeypairRef;
15use zeroize::Zeroizing;
16
17const POINT_SIZE: usize = 97;
18
19/// ML-DSA-87 and ECDSA P-384 composite public key.
20#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
21pub struct MlDsa87P384PublicKey {
22    pub(super) mldsa: PublicKeyBytes<MlDsa87>,
23    pub(super) p384: p384::Sec1Point,
24}
25
26impl MlDsa87P384PublicKey {
27    /// Size of the composite public key inside its outer SSH string.
28    pub const BYTE_SIZE: usize = size_of::<EncodedVerifyingKey<MlDsa87>>() + 4 + POINT_SIZE;
29
30    /// Get the SSH algorithm for this key.
31    #[must_use]
32    pub fn algorithm(&self) -> Algorithm {
33        Algorithm::MlDsa87P384
34    }
35}
36
37impl Decode for MlDsa87P384PublicKey {
38    type Error = Error;
39
40    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
41        reader.read_prefixed(|reader| {
42            if reader.remaining_len() != Self::BYTE_SIZE {
43                return Err(encoding::Error::Length.into());
44            }
45            let mut mldsa = PublicKeyBytes::<MlDsa87>::default();
46            reader.read(mldsa.as_mut_slice())?;
47            // Only an uncompressed SEC1 point has this length.
48            let point = reader.read_prefixed(<[u8; POINT_SIZE]>::decode)?;
49            let p384 = p384::Sec1Point::from_bytes(point)?;
50            p384::PublicKey::try_from(&p384).map_err(|_| Error::PublicKey)?;
51            Ok(Self { mldsa, p384 })
52        })
53    }
54}
55
56impl Encode for MlDsa87P384PublicKey {
57    fn encoded_len(&self) -> encoding::Result<usize> {
58        Ok(4 + Self::BYTE_SIZE)
59    }
60
61    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
62        Self::BYTE_SIZE.encode(writer)?;
63        writer.write(self.mldsa.as_slice())?;
64        self.p384.as_bytes().encode(writer)
65    }
66}
67
68/// ML-DSA seed and P-384 private scalar dedicated to this composite key.
69#[derive(Clone)]
70pub struct MlDsa87P384PrivateKey {
71    pub(super) mldsa: Zeroizing<Seed>,
72    pub(super) p384: p384::SecretKey,
73}
74
75impl MlDsa87P384PrivateKey {
76    /// Construct a private key from its dedicated components.
77    #[must_use]
78    pub fn new(mldsa: Seed, p384: p384::SecretKey) -> Self {
79        Self {
80            mldsa: Zeroizing::new(mldsa),
81            p384,
82        }
83    }
84
85    /// Generate both components independently.
86    pub fn random<R: CryptoRng + ?Sized>(rng: &mut R) -> Self {
87        let mut seed = Seed::default();
88        rng.fill_bytes(&mut seed);
89        Self::new(seed, p384::SecretKey::generate_from_rng(rng))
90    }
91
92    /// Derive the composite public key.
93    #[must_use]
94    pub fn public_key(&self) -> MlDsa87P384PublicKey {
95        MlDsa87P384PublicKey {
96            mldsa: derive_public_key::<MlDsa87>(&self.mldsa),
97            p384: self.p384.public_key().to_sec1_point(false),
98        }
99    }
100
101    pub(crate) fn checkint_bytes(&self) -> &[u8] {
102        self.mldsa.as_slice()
103    }
104}
105
106impl Decode for MlDsa87P384PrivateKey {
107    type Error = Error;
108
109    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
110        reader.read_prefixed(|reader| {
111            let mut mldsa = Seed::default();
112            reader.read(&mut mldsa)?;
113            // A P-384 scalar takes at most 48 bytes plus an optional sign byte.
114            if reader.remaining_len() > 4 + 1 + size_of::<p384::FieldBytes>() {
115                return Err(encoding::Error::Length.into());
116            }
117            let mut bytes = Zeroizing::new(p384::FieldBytes::default());
118            reader.read_mpint_bytes(&mut bytes)?;
119            let p384 = p384::SecretKey::from_bytes(&bytes).map_err(|_| Error::Crypto)?;
120            Ok(Self::new(mldsa, p384))
121        })
122    }
123}
124
125impl Encode for MlDsa87P384PrivateKey {
126    fn encoded_len(&self) -> encoding::Result<usize> {
127        let bytes = Zeroizing::new(self.p384.to_bytes());
128        [
129            4,
130            size_of::<Seed>(),
131            MpintRef::from_bytes(&bytes)?.encoded_len()?,
132        ]
133        .checked_sum()
134    }
135
136    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
137        let bytes = Zeroizing::new(self.p384.to_bytes());
138        let d = MpintRef::from_bytes(&bytes)?;
139        [size_of::<Seed>(), d.encoded_len()?]
140            .checked_sum()?
141            .encode(writer)?;
142        writer.write(self.mldsa.as_slice())?;
143        d.encode(writer)
144    }
145}
146
147impl CtEq for MlDsa87P384PrivateKey {
148    fn ct_eq(&self, other: &Self) -> Choice {
149        self.mldsa.as_slice().ct_eq(other.mldsa.as_slice())
150            & Choice::from(u8::from(self.p384 == other.p384))
151    }
152}
153
154impl PartialEq for MlDsa87P384PrivateKey {
155    fn eq(&self, other: &Self) -> bool {
156        self.ct_eq(other).into()
157    }
158}
159
160impl Eq for MlDsa87P384PrivateKey {}
161
162impl fmt::Debug for MlDsa87P384PrivateKey {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        f.debug_struct("MlDsa87P384PrivateKey")
165            .finish_non_exhaustive()
166    }
167}
168
169/// ML-DSA-87 and ECDSA P-384 composite keypair.
170#[derive(Clone, Debug, Encode)]
171pub struct MlDsa87P384Keypair {
172    public: MlDsa87P384PublicKey,
173    private: MlDsa87P384PrivateKey,
174}
175
176impl MlDsa87P384Keypair {
177    /// Generate a random composite keypair.
178    pub fn random<R: CryptoRng + ?Sized>(rng: &mut R) -> Self {
179        MlDsa87P384PrivateKey::random(rng).into()
180    }
181
182    /// Get the SSH algorithm for this keypair.
183    #[must_use]
184    pub fn algorithm(&self) -> Algorithm {
185        self.public.algorithm()
186    }
187
188    /// Borrow the composite private key.
189    #[must_use]
190    pub fn private(&self) -> &MlDsa87P384PrivateKey {
191        &self.private
192    }
193}
194
195impl From<MlDsa87P384PrivateKey> for MlDsa87P384Keypair {
196    fn from(private: MlDsa87P384PrivateKey) -> Self {
197        Self {
198            public: private.public_key(),
199            private,
200        }
201    }
202}
203
204impl AsRef<MlDsa87P384PublicKey> for MlDsa87P384Keypair {
205    fn as_ref(&self) -> &MlDsa87P384PublicKey {
206        &self.public
207    }
208}
209
210impl KeypairRef for MlDsa87P384Keypair {
211    type VerifyingKey = MlDsa87P384PublicKey;
212}
213
214impl From<MlDsa87P384Keypair> for MlDsa87P384PublicKey {
215    fn from(keypair: MlDsa87P384Keypair) -> Self {
216        keypair.public
217    }
218}
219
220impl From<&MlDsa87P384Keypair> for MlDsa87P384PublicKey {
221    fn from(keypair: &MlDsa87P384Keypair) -> Self {
222        keypair.public.clone()
223    }
224}
225
226impl CtEq for MlDsa87P384Keypair {
227    fn ct_eq(&self, other: &Self) -> Choice {
228        self.private.ct_eq(&other.private)
229    }
230}
231
232impl PartialEq for MlDsa87P384Keypair {
233    fn eq(&self, other: &Self) -> bool {
234        self.ct_eq(other).into()
235    }
236}
237
238impl Eq for MlDsa87P384Keypair {}
239
240impl Decode for MlDsa87P384Keypair {
241    type Error = Error;
242
243    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
244        let public = MlDsa87P384PublicKey::decode(reader)?;
245        let private = MlDsa87P384PrivateKey::decode(reader)?;
246        if private.public_key() != public {
247            return Err(Error::PublicKey);
248        }
249        Ok(Self { public, private })
250    }
251}