Skip to main content

quantaegis_hybrid/
mldsa65_ed25519.rs

1//! **IETF LAMPS Composite ML-DSA (`id-MLDSA65-Ed25519-SHA512`)** hybrid digital signature scheme.
2//!
3//! Conforms to **RFC 10073** (`draft-ietf-lamps-pq-composite-sigs-19`, OID `1.3.6.1.5.5.7.6.48`),
4//! combining **NIST FIPS 204 ML-DSA-65** (NIST Security Category 3) with **RFC 8032 Ed25519**
5//! using **SHA-512** pre-hashing and mandatory domain separation:
6//!
7//! ```text
8//! Prefix = "CompositeAlgorithmSignatures2025"  (32 bytes)
9//! Label  = "COMPSIG-MLDSA65-Ed25519-SHA512"    (30 bytes)
10//! M'     = Prefix || Label || len(ctx) || ctx || SHA512(M)
11//! sig    = ML-DSA-65.Sign(sk_mldsa, M', ctx = Label) || Ed25519.Sign(sk_ed, M')
12//! ```
13//!
14//! Verified against the official `lamps-wg/draft-composite-sigs` (`RFC 10073` / `-19`)
15//! `id-MLDSA65-Ed25519-SHA512` test vectors (both empty and non-empty context).
16//!
17//! # Security Properties
18//! - **Hybrid AND-Gate**: Verification succeeds if and only if **both** ML-DSA-65 and Ed25519
19//!   verify cleanly over `M'`, preserving EUF-CMA unforgeability as long as either primitive holds.
20//! - **Anti-stripping domain separation**: Binding `Label` into both `M'` and the ML-DSA-65
21//!   internal context string prevents cross-protocol component-signature reuse.
22//! - **Compact 64-byte composite seed**: `sk = seed_mldsa65 (32 B) || seed_ed25519 (32 B)`.
23//! - `#![no_std]` (zero heap allocation) and `#![forbid(unsafe_code)]`.
24
25use core::fmt;
26
27use ed25519_dalek::{Signature as EdSignature, Signer as _, SigningKey as EdSigningKey};
28use quantaegis_core::{
29    CryptoRng, Error, Result, SecretBytes, Signature as SignatureTrait, Zeroize,
30};
31use quantaegis_ml_dsa::{MlDsa65, ml_dsa_65};
32use sha2::{Digest as _, Sha512};
33
34/// IETF LAMPS composite signature prefix (`"CompositeAlgorithmSignatures2025"`, 32 bytes).
35pub const PREFIX: &[u8; 32] = b"CompositeAlgorithmSignatures2025";
36
37/// Algorithm-specific domain separator (`"COMPSIG-MLDSA65-Ed25519-SHA512"`, 30 bytes).
38pub const LABEL: &[u8; 30] = b"COMPSIG-MLDSA65-Ed25519-SHA512";
39
40/// Maximum application context string length (`255` bytes).
41pub const MAX_CTX_LEN: usize = 255;
42
43/// Composite public verifying key length: `1952 (ML-DSA-65) + 32 (Ed25519) = 1984` bytes.
44pub const PK_LEN: usize = ml_dsa_65::PK_LEN + 32;
45
46/// Composite private signing key length: `32 (ML-DSA-65 seed) + 32 (Ed25519 seed) = 64` bytes.
47pub const SK_LEN: usize = 64;
48
49/// Composite signature length: `3309 (ML-DSA-65) + 64 (Ed25519) = 3373` bytes.
50pub const SIG_LEN: usize = ml_dsa_65::SIG_LEN + 64;
51
52/// Maximum encoded length of `M' = Prefix (32) || Label (30) || len(ctx) (1) || ctx (255) || SHA512 (64)`.
53const MAX_M_PRIME_LEN: usize = 32 + 30 + 1 + MAX_CTX_LEN + 64;
54
55/// Builds `M' = Prefix || Label || len(ctx) || ctx || SHA512(msg)` on the stack (no heap alloc).
56fn build_m_prime(msg: &[u8], ctx: &[u8]) -> Result<([u8; MAX_M_PRIME_LEN], usize)> {
57    if ctx.len() > MAX_CTX_LEN {
58        return Err(Error::ContextTooLong {
59            max: MAX_CTX_LEN,
60            actual: ctx.len(),
61        });
62    }
63    let ph = Sha512::digest(msg);
64    let mut buf = [0u8; MAX_M_PRIME_LEN];
65    let mut off = 0usize;
66
67    buf[off..off + PREFIX.len()].copy_from_slice(PREFIX);
68    off += PREFIX.len();
69    buf[off..off + LABEL.len()].copy_from_slice(LABEL);
70    off += LABEL.len();
71    #[allow(clippy::cast_possible_truncation)]
72    {
73        buf[off] = ctx.len() as u8;
74    }
75    off += 1;
76    buf[off..off + ctx.len()].copy_from_slice(ctx);
77    off += ctx.len();
78    buf[off..off + 64].copy_from_slice(&ph);
79    off += 64;
80
81    Ok((buf, off))
82}
83
84/// Composite verifying key (`pk_mldsa65[1952] || pk_ed25519[32]`).
85#[derive(Clone, Eq, PartialEq)]
86pub struct VerifyingKey {
87    bytes: [u8; PK_LEN],
88}
89
90impl VerifyingKey {
91    /// Parses and validates a 1,984-byte composite verifying key (checks Ed25519 point encoding).
92    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
93        if bytes.len() != PK_LEN {
94            return Err(Error::InvalidLength {
95                expected: PK_LEN,
96                actual: bytes.len(),
97            });
98        }
99        let mut ed_pk = [0u8; 32];
100        ed_pk.copy_from_slice(&bytes[ml_dsa_65::PK_LEN..]);
101        let _ = ed25519_dalek::VerifyingKey::from_bytes(&ed_pk)
102            .map_err(|_| Error::InvalidVerifyingKey)?;
103
104        let mut arr = [0u8; PK_LEN];
105        arr.copy_from_slice(bytes);
106        Ok(Self { bytes: arr })
107    }
108
109    /// Returns the canonical 1,984-byte composite public key.
110    #[inline]
111    pub const fn as_bytes(&self) -> &[u8; PK_LEN] {
112        &self.bytes
113    }
114
115    /// Verifies `sig` over `msg` and `ctx` — requires **both** ML-DSA-65 and Ed25519 to succeed.
116    pub fn verify(&self, msg: &[u8], ctx: &[u8], sig: &Signature) -> Result<()> {
117        let (m_prime_buf, m_prime_len) = build_m_prime(msg, ctx)?;
118        let m_prime = &m_prime_buf[..m_prime_len];
119
120        // 1. Verify Ed25519 component strictly (fast reject on invalid classical component).
121        let mut ed_pk_bytes = [0u8; 32];
122        ed_pk_bytes.copy_from_slice(&self.bytes[ml_dsa_65::PK_LEN..]);
123        let ed_pub = ed25519_dalek::VerifyingKey::from_bytes(&ed_pk_bytes)
124            .map_err(|_| Error::InvalidVerifyingKey)?;
125        let mut ed_sig_bytes = [0u8; 64];
126        ed_sig_bytes.copy_from_slice(&sig.bytes[ml_dsa_65::SIG_LEN..]);
127        let ed_sig = EdSignature::from_bytes(&ed_sig_bytes);
128        let classical_valid = ed_pub.verify_strict(m_prime, &ed_sig).is_ok();
129
130        // 2. Verify ML-DSA-65 component with internal context `LABEL`.
131        let pq_pub = ml_dsa_65::VerifyingKey::from_bytes(&self.bytes[..ml_dsa_65::PK_LEN])?;
132        let mldsa_sig = ml_dsa_65::Signature::from_bytes(&sig.bytes[..ml_dsa_65::SIG_LEN])?;
133        let pq_valid = MlDsa65::verify(&pq_pub, m_prime, LABEL, &mldsa_sig).is_ok();
134
135        if classical_valid && pq_valid {
136            Ok(())
137        } else {
138            Err(Error::InvalidSignature)
139        }
140    }
141}
142
143impl fmt::Debug for VerifyingKey {
144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145        write!(f, "MlDsa65Ed25519::VerifyingKey([{PK_LEN} bytes])")
146    }
147}
148
149/// Compact 64-byte composite signing key seed (`seed_mldsa65[32] || seed_ed25519[32]`).
150///
151/// Automatically zeroized on drop and redacted in `Debug`.
152pub struct SigningKey {
153    seed: SecretBytes<SK_LEN>,
154}
155
156impl SigningKey {
157    /// Parses a 64-byte composite signing key seed.
158    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
159        if bytes.len() != SK_LEN {
160            return Err(Error::InvalidLength {
161                expected: SK_LEN,
162                actual: bytes.len(),
163            });
164        }
165        let mut arr = [0u8; SK_LEN];
166        arr.copy_from_slice(bytes);
167        let seed = SecretBytes::new(arr);
168        arr.zeroize();
169        Ok(Self { seed })
170    }
171
172    /// Exposes the raw 64-byte composite seed (handle with extreme care!).
173    #[inline]
174    pub fn expose_bytes(&self) -> &[u8; SK_LEN] {
175        self.seed.expose_secret()
176    }
177
178    /// Derives the corresponding 1,984-byte composite verifying key.
179    pub fn verifying_key(&self) -> VerifyingKey {
180        let mut mldsa_seed = [0u8; 32];
181        let mut ed_seed = [0u8; 32];
182        mldsa_seed.copy_from_slice(&self.seed.expose_secret()[..32]);
183        ed_seed.copy_from_slice(&self.seed.expose_secret()[32..]);
184
185        let (pq_pub, mut pq_sec) = MlDsa65::from_seed(&mldsa_seed);
186        let ed_sec = EdSigningKey::from_bytes(&ed_seed);
187        let ed_pub = ed_sec.verifying_key();
188
189        let mut pk = [0u8; PK_LEN];
190        pk[..ml_dsa_65::PK_LEN].copy_from_slice(pq_pub.as_bytes());
191        pk[ml_dsa_65::PK_LEN..].copy_from_slice(ed_pub.as_bytes());
192
193        mldsa_seed.zeroize();
194        ed_seed.zeroize();
195        pq_sec.zeroize();
196        VerifyingKey { bytes: pk }
197    }
198
199    /// Signs `msg` with context `ctx` (hedged ML-DSA-65 + RFC 8032 Ed25519).
200    pub fn sign<R: CryptoRng + ?Sized>(
201        &self,
202        msg: &[u8],
203        ctx: &[u8],
204        rng: &mut R,
205    ) -> Result<Signature> {
206        let (m_prime_buf, m_prime_len) = build_m_prime(msg, ctx)?;
207        let m_prime = &m_prime_buf[..m_prime_len];
208
209        let (_, mut mldsa_sk) = {
210            let mut mldsa_seed = SecretBytes::new([0u8; 32]);
211            mldsa_seed
212                .expose_secret_mut()
213                .copy_from_slice(&self.seed.expose_secret()[..32]);
214            MlDsa65::from_seed(mldsa_seed.expose_secret())
215        };
216        let mldsa_sig_res = MlDsa65::sign(&mldsa_sk, m_prime, LABEL, rng);
217        mldsa_sk.zeroize();
218        let mldsa_sig = mldsa_sig_res?;
219
220        let ed_sk = {
221            let mut ed_seed = SecretBytes::new([0u8; 32]);
222            ed_seed
223                .expose_secret_mut()
224                .copy_from_slice(&self.seed.expose_secret()[32..]);
225            EdSigningKey::from_bytes(ed_seed.expose_secret())
226        };
227        let ed_sig = ed_sk.sign(m_prime);
228
229        let mut out = [0u8; SIG_LEN];
230        out[..ml_dsa_65::SIG_LEN].copy_from_slice(mldsa_sig.as_bytes());
231        out[ml_dsa_65::SIG_LEN..].copy_from_slice(&ed_sig.to_bytes());
232        Ok(Signature { bytes: out })
233    }
234
235    /// Signs `msg` with context `ctx` deterministically (deterministic ML-DSA-65 + RFC 8032 Ed25519).
236    pub fn sign_deterministic(&self, msg: &[u8], ctx: &[u8]) -> Result<Signature> {
237        let (m_prime_buf, m_prime_len) = build_m_prime(msg, ctx)?;
238        let m_prime = &m_prime_buf[..m_prime_len];
239
240        let (_, mut mldsa_sk) = {
241            let mut mldsa_seed = SecretBytes::new([0u8; 32]);
242            mldsa_seed
243                .expose_secret_mut()
244                .copy_from_slice(&self.seed.expose_secret()[..32]);
245            MlDsa65::from_seed(mldsa_seed.expose_secret())
246        };
247        let mldsa_sig_res = MlDsa65::sign_deterministic(&mldsa_sk, m_prime, LABEL);
248        mldsa_sk.zeroize();
249        let mldsa_sig = mldsa_sig_res?;
250
251        let ed_sk = {
252            let mut ed_seed = SecretBytes::new([0u8; 32]);
253            ed_seed
254                .expose_secret_mut()
255                .copy_from_slice(&self.seed.expose_secret()[32..]);
256            EdSigningKey::from_bytes(ed_seed.expose_secret())
257        };
258        let ed_sig = ed_sk.sign(m_prime);
259
260        let mut out = [0u8; SIG_LEN];
261        out[..ml_dsa_65::SIG_LEN].copy_from_slice(mldsa_sig.as_bytes());
262        out[ml_dsa_65::SIG_LEN..].copy_from_slice(&ed_sig.to_bytes());
263        Ok(Signature { bytes: out })
264    }
265}
266
267impl Zeroize for SigningKey {
268    #[inline]
269    fn zeroize(&mut self) {
270        self.seed.zeroize();
271    }
272}
273
274impl fmt::Debug for SigningKey {
275    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276        write!(f, "MlDsa65Ed25519::SigningKey([REDACTED])")
277    }
278}
279
280/// Composite signature (`sig_mldsa65[3309] || sig_ed25519[64]`, 3,373 bytes).
281#[derive(Clone, Eq, PartialEq)]
282pub struct Signature {
283    bytes: [u8; SIG_LEN],
284}
285
286impl Signature {
287    /// Parses a 3,373-byte composite signature.
288    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
289        if bytes.len() != SIG_LEN {
290            return Err(Error::InvalidLength {
291                expected: SIG_LEN,
292                actual: bytes.len(),
293            });
294        }
295        let mut arr = [0u8; SIG_LEN];
296        arr.copy_from_slice(bytes);
297        Ok(Self { bytes: arr })
298    }
299
300    /// Returns the canonical 3,373-byte signature representation.
301    #[inline]
302    pub const fn as_bytes(&self) -> &[u8; SIG_LEN] {
303        &self.bytes
304    }
305}
306
307impl fmt::Debug for Signature {
308    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309        write!(f, "MlDsa65Ed25519::Signature([{SIG_LEN} bytes])")
310    }
311}
312
313/// Marker struct implementing [`quantaegis_core::Signature`] for **IETF LAMPS `MLDSA65-Ed25519-SHA512`**.
314pub struct MlDsa65Ed25519;
315
316impl MlDsa65Ed25519 {
317    /// Derives a `(VerifyingKey, SigningKey)` pair deterministically from a 64-byte composite seed
318    /// (`mldsa65_seed[32] || ed25519_seed[32]`).
319    pub fn from_seed(seed: &[u8; SK_LEN]) -> (VerifyingKey, SigningKey) {
320        let sk = SigningKey {
321            seed: SecretBytes::new(*seed),
322        };
323        let vk = sk.verifying_key();
324        (vk, sk)
325    }
326
327    /// Signs `msg` with context `ctx` in deterministic mode.
328    pub fn sign_deterministic(sk: &SigningKey, msg: &[u8], ctx: &[u8]) -> Result<Signature> {
329        sk.sign_deterministic(msg, ctx)
330    }
331}
332
333impl SignatureTrait for MlDsa65Ed25519 {
334    type VerifyingKey = VerifyingKey;
335    type SigningKey = SigningKey;
336    type Sig = Signature;
337
338    fn keygen<R: CryptoRng + ?Sized>(
339        rng: &mut R,
340    ) -> Result<(Self::VerifyingKey, Self::SigningKey)> {
341        let mut seed = SecretBytes::new([0u8; SK_LEN]);
342        rng.try_fill_bytes(seed.expose_secret_mut())?;
343        Ok(Self::from_seed(seed.expose_secret()))
344    }
345
346    fn sign<R: CryptoRng + ?Sized>(
347        sk: &Self::SigningKey,
348        msg: &[u8],
349        ctx: &[u8],
350        rng: &mut R,
351    ) -> Result<Self::Sig> {
352        sk.sign(msg, ctx, rng)
353    }
354
355    fn verify(vk: &Self::VerifyingKey, msg: &[u8], ctx: &[u8], sig: &Self::Sig) -> Result<()> {
356        vk.verify(msg, ctx, sig)
357    }
358}
359
360#[cfg(test)]
361mod tests {
362    use super::*;
363    use quantaegis_sha3::{Sha3_256, Shake128};
364
365    fn to_hex(bytes: &[u8]) -> [u8; 64] {
366        const HEX: &[u8; 16] = b"0123456789abcdef";
367        let mut out = [0u8; 64];
368        for (i, &b) in bytes.iter().take(32).enumerate() {
369            out[2 * i] = HEX[usize::from(b >> 4)];
370            out[2 * i + 1] = HEX[usize::from(b & 0x0F)];
371        }
372        out
373    }
374
375    struct TestRng(quantaegis_sha3::Shake128Reader);
376    impl CryptoRng for TestRng {
377        fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<()> {
378            self.0.squeeze(dest);
379            Ok(())
380        }
381    }
382
383    #[test]
384    fn mldsa65_ed25519_matches_independent_go_stdlib_kat() {
385        let mut seed = [0u8; SK_LEN];
386        for i in 0..32 {
387            #[allow(clippy::cast_possible_truncation)]
388            {
389                seed[i] = (0x10 + i) as u8;
390                seed[32 + i] = (0x50 + i) as u8;
391            }
392        }
393        let (vk, sk) = MlDsa65Ed25519::from_seed(&seed);
394        let msg = b"IETF LAMPS Composite MLDSA65-Ed25519-SHA512 KAT message";
395        let ctx = b"hybrid-release-v1";
396
397        let sig = MlDsa65Ed25519::sign_deterministic(&sk, msg, ctx)
398            .ok()
399            .unwrap_or_else(|| unreachable!());
400        assert_eq!(MlDsa65Ed25519::verify(&vk, msg, ctx, &sig), Ok(()));
401
402        assert_eq!(
403            &to_hex(&Sha3_256::digest(vk.as_bytes())),
404            b"a658289d6190d7575a65e90a2f99600a35892eebadc3540ff67f1eba78936dbc"
405        );
406        assert_eq!(
407            &to_hex(&Sha3_256::digest(sig.as_bytes())),
408            b"7b00df25673fca4c696719ae679d4726bd8c299997a08b9f7c187db858c39123"
409        );
410    }
411
412    #[test]
413    fn mldsa65_ed25519_and_gate_rejects_either_component_tamper() {
414        let mut h = Shake128::new();
415        h.update(b"composite-and-gate-test");
416        let mut rng = TestRng(h.finalize_xof());
417
418        let (vk, sk) = MlDsa65Ed25519::keygen(&mut rng)
419            .ok()
420            .unwrap_or_else(|| unreachable!());
421        let msg = b"dual-signature security invariant";
422        let ctx = b"audit-v1";
423        let sig = MlDsa65Ed25519::sign(&sk, msg, ctx, &mut rng)
424            .ok()
425            .unwrap_or_else(|| unreachable!());
426        assert_eq!(MlDsa65Ed25519::verify(&vk, msg, ctx, &sig), Ok(()));
427
428        // Flip 1 bit in ML-DSA-65 half -> MUST reject even though Ed25519 still matches!
429        let mut bad_pq = *sig.as_bytes();
430        bad_pq[0] ^= 0x01;
431        let bad_pq_sig = Signature::from_bytes(&bad_pq)
432            .ok()
433            .unwrap_or_else(|| unreachable!());
434        assert_eq!(
435            MlDsa65Ed25519::verify(&vk, msg, ctx, &bad_pq_sig),
436            Err(Error::InvalidSignature)
437        );
438
439        // Flip 1 bit in Ed25519 half -> MUST reject even though ML-DSA-65 still matches!
440        let mut bad_ed = *sig.as_bytes();
441        bad_ed[SIG_LEN - 1] ^= 0x01;
442        let bad_ed_sig = Signature::from_bytes(&bad_ed)
443            .ok()
444            .unwrap_or_else(|| unreachable!());
445        assert_eq!(
446            MlDsa65Ed25519::verify(&vk, msg, ctx, &bad_ed_sig),
447            Err(Error::InvalidSignature)
448        );
449
450        // Wrong context -> MUST reject
451        assert_eq!(
452            MlDsa65Ed25519::verify(&vk, msg, b"wrong", &sig),
453            Err(Error::InvalidSignature)
454        );
455    }
456
457    #[test]
458    fn sign_propagates_rng_failure() {
459        struct FailRng;
460        impl CryptoRng for FailRng {
461            fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<()> {
462                let half = dest.len() / 2;
463                dest[..half].fill(0xA5);
464                Err(Error::RngFailure)
465            }
466        }
467
468        let (_vk, sk) = MlDsa65Ed25519::from_seed(&[0x33u8; SK_LEN]);
469        let mut rng = FailRng;
470        assert_eq!(
471            MlDsa65Ed25519::sign(&sk, b"msg", b"ctx", &mut rng),
472            Err(Error::RngFailure)
473        );
474    }
475}