Skip to main content

ssh_key/composite/mldsa44_ed25519/
keys.rs

1//! Keys for the ML-DSA-44 and Ed25519 composite signature algorithm.
2
3use crate::{
4    Algorithm, Error, Result,
5    composite::{PublicKeyBytes, derive_public_key},
6    private::Ed25519PrivateKey,
7    public::Ed25519PublicKey,
8};
9use core::fmt;
10use ctutils::{Choice, CtEq};
11use encoding::{CheckedSum, Decode, Decoder, Encode, Reader, Writer};
12use ml_dsa::{EncodedSignature, EncodedVerifyingKey, MlDsa44, Seed};
13use rand_core::CryptoRng;
14use signature::{Keypair, KeypairRef};
15use zeroize::Zeroizing;
16
17#[cfg(feature = "alloc")]
18use alloc::vec::Vec;
19
20/// MLDSA44-Ed25519-SHA512 composite public key.
21///
22/// Encoded as the 1312-byte ML-DSA public key followed by the 32-byte Ed25519 public key.
23#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
24pub struct MlDsa44Ed25519PublicKey {
25    pub(super) mldsa: PublicKeyBytes<MlDsa44>,
26    ed25519: Ed25519PublicKey,
27}
28
29impl MlDsa44Ed25519PublicKey {
30    /// Size of an encoded composite public key in bytes.
31    pub const BYTE_SIZE: usize =
32        size_of::<EncodedVerifyingKey<MlDsa44>>() + Ed25519PublicKey::BYTE_SIZE;
33
34    /// Size of an encoded composite signature in bytes.
35    pub const SIGNATURE_SIZE: usize =
36        size_of::<EncodedSignature<MlDsa44>>() + ed25519_dalek::SIGNATURE_LENGTH;
37
38    /// Parse the concatenated ML-DSA and Ed25519 public keys.
39    ///
40    /// # Errors
41    /// Returns [`encoding::Error::Length`] if the input has the wrong length.
42    pub fn new(key: impl AsRef<[u8]>) -> Result<Self> {
43        Self::decode_bytes(&mut Decoder::from_bytes(key.as_ref())?)
44    }
45
46    /// Get the SSH algorithm for this public key.
47    #[must_use]
48    pub fn algorithm(&self) -> Algorithm {
49        Algorithm::MlDsa44Ed25519
50    }
51
52    /// Borrow the Ed25519 component. Component keys must be used exclusively in this composite.
53    #[must_use]
54    pub fn ed25519(&self) -> &Ed25519PublicKey {
55        &self.ed25519
56    }
57
58    /// Get the concatenated encoding of both public keys.
59    #[cfg(feature = "alloc")]
60    #[must_use]
61    pub fn to_bytes(&self) -> Vec<u8> {
62        let mut bytes = Vec::with_capacity(Self::BYTE_SIZE);
63        bytes.extend_from_slice(self.mldsa.as_slice());
64        bytes.extend_from_slice(self.ed25519.as_ref());
65        bytes
66    }
67
68    fn decode_bytes(reader: &mut Decoder<impl Reader>) -> Result<Self> {
69        if reader.remaining_len() != Self::BYTE_SIZE {
70            return Err(encoding::Error::Length.into());
71        }
72        let mut mldsa = PublicKeyBytes::<MlDsa44>::default();
73        reader.read(mldsa.as_mut_slice())?;
74        let ed25519 = Ed25519PublicKey(Decode::decode(reader)?);
75        Ok(Self { mldsa, ed25519 })
76    }
77}
78
79impl TryFrom<&[u8]> for MlDsa44Ed25519PublicKey {
80    type Error = Error;
81
82    fn try_from(bytes: &[u8]) -> Result<Self> {
83        Self::new(bytes)
84    }
85}
86
87impl Decode for MlDsa44Ed25519PublicKey {
88    type Error = Error;
89
90    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
91        reader.read_prefixed(Self::decode_bytes)
92    }
93}
94
95impl Encode for MlDsa44Ed25519PublicKey {
96    fn encoded_len(&self) -> encoding::Result<usize> {
97        Ok(4 + Self::BYTE_SIZE)
98    }
99
100    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
101        Self::BYTE_SIZE.encode(writer)?;
102        writer.write(self.mldsa.as_slice())?;
103        writer.write(self.ed25519.as_ref())
104    }
105}
106
107impl fmt::Display for MlDsa44Ed25519PublicKey {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        for byte in self.mldsa.as_slice() {
110            write!(f, "{byte:02x}")?;
111        }
112        write!(f, "{:x}", self.ed25519)
113    }
114}
115
116/// MLDSA44-Ed25519-SHA512 composite private key.
117///
118/// Stores the ML-DSA seed followed by the Ed25519 seed. Each is 32 bytes.
119#[derive(Clone)]
120pub struct MlDsa44Ed25519PrivateKey {
121    pub(super) mldsa: Zeroizing<Seed>,
122    ed25519: Ed25519PrivateKey,
123}
124
125impl MlDsa44Ed25519PrivateKey {
126    /// Size of an encoded composite private key in bytes.
127    pub const BYTE_SIZE: usize = size_of::<Seed>() + Ed25519PrivateKey::BYTE_SIZE;
128
129    /// Generate fresh seeds for both components.
130    ///
131    /// # Errors
132    /// Propagates errors from [`Self::from_bytes`].
133    pub fn random<R: CryptoRng + ?Sized>(rng: &mut R) -> Result<Self> {
134        let mut seed = Zeroizing::new([0u8; Self::BYTE_SIZE]);
135        rng.fill_bytes(seed.as_mut_slice());
136        Self::from_bytes(&seed)
137    }
138
139    /// Parse the two concatenated seeds. Both must be dedicated to this composite key.
140    ///
141    /// # Errors
142    /// Returns [`encoding::Error::Length`] if either seed has the wrong length.
143    /// The fixed-size input guarantees the required lengths.
144    pub fn from_bytes(bytes: &[u8; Self::BYTE_SIZE]) -> Result<Self> {
145        let (mldsa, ed25519) = bytes.split_at(size_of::<Seed>());
146        Ok(Self {
147            mldsa: Zeroizing::new(mldsa.try_into()?),
148            ed25519: ed25519.try_into()?,
149        })
150    }
151
152    /// Get the concatenated encoding of both private seeds.
153    #[must_use]
154    pub fn to_bytes(&self) -> [u8; Self::BYTE_SIZE] {
155        let mut bytes = [0u8; Self::BYTE_SIZE];
156        let (mldsa, ed25519) = bytes.split_at_mut(size_of::<Seed>());
157        mldsa.copy_from_slice(self.mldsa.as_slice());
158        ed25519.copy_from_slice(self.ed25519.as_ref());
159        bytes
160    }
161
162    /// Borrow the Ed25519 component. Component keys must be used exclusively in this composite.
163    #[must_use]
164    pub fn ed25519(&self) -> &Ed25519PrivateKey {
165        &self.ed25519
166    }
167
168    /// Derive the composite public key from both seeds.
169    ///
170    /// # Errors
171    /// Key derivation for these fixed-size seeds is infallible.
172    pub fn public_key(&self) -> Result<MlDsa44Ed25519PublicKey> {
173        Ok(MlDsa44Ed25519PublicKey {
174            mldsa: derive_public_key::<MlDsa44>(&self.mldsa),
175            ed25519: Ed25519PublicKey::from(&self.ed25519),
176        })
177    }
178
179    /// Private key material used for the deterministic checkint hash.
180    pub(crate) fn checkint_bytes(&self) -> &[u8] {
181        self.mldsa.as_slice()
182    }
183}
184
185impl TryFrom<&[u8]> for MlDsa44Ed25519PrivateKey {
186    type Error = Error;
187
188    fn try_from(bytes: &[u8]) -> Result<Self> {
189        Self::from_bytes(bytes.try_into()?)
190    }
191}
192
193impl CtEq for MlDsa44Ed25519PrivateKey {
194    fn ct_eq(&self, other: &Self) -> Choice {
195        self.mldsa.as_slice().ct_eq(other.mldsa.as_slice()) & self.ed25519.ct_eq(&other.ed25519)
196    }
197}
198
199impl Eq for MlDsa44Ed25519PrivateKey {}
200
201impl PartialEq for MlDsa44Ed25519PrivateKey {
202    fn eq(&self, other: &Self) -> bool {
203        self.ct_eq(other).into()
204    }
205}
206
207impl fmt::Debug for MlDsa44Ed25519PrivateKey {
208    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209        f.debug_struct("MlDsa44Ed25519PrivateKey")
210            .finish_non_exhaustive()
211    }
212}
213
214/// MLDSA44-Ed25519-SHA512 composite keypair.
215///
216/// OpenSSH encodes the public key and the concatenated private seeds as two SSH strings.
217#[derive(Clone)]
218pub struct MlDsa44Ed25519Keypair {
219    /// Public key.
220    pub public: MlDsa44Ed25519PublicKey,
221    /// Private key.
222    pub private: MlDsa44Ed25519PrivateKey,
223}
224
225impl MlDsa44Ed25519Keypair {
226    /// Generate a random composite keypair.
227    ///
228    /// # Errors
229    /// Propagates errors from private key generation and public key derivation.
230    pub fn random<R: CryptoRng + ?Sized>(rng: &mut R) -> Result<Self> {
231        Self::new(MlDsa44Ed25519PrivateKey::random(rng)?)
232    }
233
234    /// Derive a keypair from its two dedicated component seeds, ML-DSA first.
235    ///
236    /// # Errors
237    /// Propagates errors from private key decoding and public key derivation.
238    pub fn from_seed(seed: &[u8; MlDsa44Ed25519PrivateKey::BYTE_SIZE]) -> Result<Self> {
239        Self::new(MlDsa44Ed25519PrivateKey::from_bytes(seed)?)
240    }
241
242    /// Get the SSH algorithm for this keypair.
243    #[must_use]
244    pub fn algorithm(&self) -> Algorithm {
245        self.public.algorithm()
246    }
247
248    fn new(private: MlDsa44Ed25519PrivateKey) -> Result<Self> {
249        Ok(Self {
250            public: private.public_key()?,
251            private,
252        })
253    }
254}
255
256impl AsRef<MlDsa44Ed25519PublicKey> for MlDsa44Ed25519Keypair {
257    fn as_ref(&self) -> &MlDsa44Ed25519PublicKey {
258        &self.public
259    }
260}
261
262impl KeypairRef for MlDsa44Ed25519Keypair {
263    type VerifyingKey = MlDsa44Ed25519PublicKey;
264}
265
266impl CtEq for MlDsa44Ed25519Keypair {
267    fn ct_eq(&self, other: &Self) -> Choice {
268        Choice::from(u8::from(self.public == other.public)) & self.private.ct_eq(&other.private)
269    }
270}
271
272impl Eq for MlDsa44Ed25519Keypair {}
273
274impl PartialEq for MlDsa44Ed25519Keypair {
275    fn eq(&self, other: &Self) -> bool {
276        self.ct_eq(other).into()
277    }
278}
279
280impl Decode for MlDsa44Ed25519Keypair {
281    type Error = Error;
282
283    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
284        let public = MlDsa44Ed25519PublicKey::decode(reader)?;
285        let mut seed = Zeroizing::new([0u8; MlDsa44Ed25519PrivateKey::BYTE_SIZE]);
286        let private =
287            MlDsa44Ed25519PrivateKey::try_from(reader.read_string_bytes(seed.as_mut_slice())?)?;
288        if private.public_key()? != public {
289            return Err(Error::PublicKey);
290        }
291        Ok(Self { public, private })
292    }
293}
294
295impl Encode for MlDsa44Ed25519Keypair {
296    fn encoded_len(&self) -> encoding::Result<usize> {
297        [
298            self.public.encoded_len()?,
299            4,
300            MlDsa44Ed25519PrivateKey::BYTE_SIZE,
301        ]
302        .checked_sum()
303    }
304
305    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
306        self.public.encode(writer)?;
307        MlDsa44Ed25519PrivateKey::BYTE_SIZE.encode(writer)?;
308        writer.write(self.private.mldsa.as_slice())?;
309        writer.write(self.private.ed25519.as_ref())
310    }
311}
312
313impl fmt::Debug for MlDsa44Ed25519Keypair {
314    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315        f.debug_struct("MlDsa44Ed25519Keypair")
316            .field("public", &self.public)
317            .finish_non_exhaustive()
318    }
319}
320
321impl From<MlDsa44Ed25519Keypair> for MlDsa44Ed25519PublicKey {
322    fn from(keypair: MlDsa44Ed25519Keypair) -> Self {
323        keypair.public
324    }
325}
326
327impl From<&MlDsa44Ed25519Keypair> for MlDsa44Ed25519PublicKey {
328    fn from(keypair: &MlDsa44Ed25519Keypair) -> Self {
329        keypair.verifying_key()
330    }
331}