Skip to main content

quantaegis_ml_dsa/
lib.rs

1//! Pure-Rust, `#![no_std]`, `#![forbid(unsafe_code)]`, zero-external-dependency implementation of
2//! **NIST FIPS 204: Module-Lattice-Based Digital Signature Standard (ML-DSA)**.
3//!
4//! Supports all three FIPS 204 parameter sets:
5//! - [`MlDsa44`] (NIST Security Category 2 — `pk = 1,312 B`, `sk = 2,560 B`, `sig = 2,420 B`)
6//! - [`MlDsa65`] (NIST Security Category 3 — `pk = 1,952 B`, `sk = 4,032 B`, `sig = 3,309 B`)
7//! - [`MlDsa87`] (NIST Security Category 5 — `pk = 2,592 B`, `sk = 4,896 B`, `sig = 4,627 B`)
8//!
9//! # Features & Standards Alignment
10//! - **Pure ML-DSA** (FIPS 204 Algorithms 1–3) with optional domain-separation context strings
11//!   `ctx` (`|ctx| <= 255` bytes).
12//! - **Hedged signing** (recommended default via [`quantaegis_core::Signature::sign`]) and
13//!   **deterministic signing** (`rnd = [0; 32]` via `sign_deterministic`).
14//! - **External-mu signing & verification** (RFC 9881 / FIPS 204 / `hazmat`) for
15//!   streaming or HSM pre-hashed workflows.
16//! - **Constant-time, division-free** `Z_8380417` arithmetic and decomposition; secret
17//!   keys zeroize automatically on drop and redact in `Debug`.
18//!
19//! > **Note**: Pre-`1.0.0` software — an independent third-party cryptographic audit has not yet
20//! > been completed; please take this into account when using this crate. The project-wide maturity
21//! > stage is tracked in one place:
22//! > [SECURITY.md](https://github.com/PyRin-c/quantaegis/blob/main/SECURITY.md#maturity--production-readiness-status).
23
24#![no_std]
25#![forbid(unsafe_code)]
26
27#[cfg(feature = "std")]
28extern crate std;
29
30mod field;
31mod mldsa;
32mod ntt;
33mod packing;
34pub mod params;
35mod poly;
36mod rounding;
37mod sampling;
38
39pub use params::{MAX_CTX_LEN, MU_LEN, RND_LEN, SEED_LEN};
40
41use core::fmt;
42use quantaegis_core::{
43    CryptoRng, Error, Result, SecretBytes, Signature as SignatureTrait, Zeroize,
44};
45use quantaegis_sha3::Shake256;
46
47/// Streaming FIPS 204 External-mu (`mu = SHAKE256(tr || 0x00 || len(ctx) || ctx || M, 64)`)
48/// hasher for large messages, file streams, and HSM pre-hashing workflows.
49///
50/// Matches the Pure ML-DSA message representative `mu` bit-for-bit regardless of how the
51/// input message is chunked across [`MuHasher::update`] calls.
52pub struct MuHasher {
53    xof: Shake256,
54}
55
56impl MuHasher {
57    /// Initializes a streaming External-mu hasher from a 64-byte public key hash `tr`
58    /// and domain-separation context `ctx` (`|ctx| <= 255`).
59    pub fn new(tr: &[u8; params::TR_LEN], ctx: &[u8]) -> Result<Self> {
60        if ctx.len() > MAX_CTX_LEN {
61            return Err(Error::ContextTooLong {
62                max: MAX_CTX_LEN,
63                actual: ctx.len(),
64            });
65        }
66        let mut xof = Shake256::new();
67        xof.update(tr);
68        #[allow(clippy::cast_possible_truncation)]
69        let prefix = [0x00u8, ctx.len() as u8];
70        xof.update(&prefix);
71        xof.update(ctx);
72        Ok(Self { xof })
73    }
74
75    /// Absorbs the next message chunk into the streaming SHAKE256 sponge.
76    #[inline]
77    pub fn update(&mut self, chunk: &[u8]) {
78        self.xof.update(chunk);
79    }
80
81    /// Finalizes the stream and returns the 64-byte FIPS 204 message representative `mu`.
82    pub fn finalize(self) -> [u8; MU_LEN] {
83        let mut mu = [0u8; MU_LEN];
84        self.xof.finalize_xof().squeeze(&mut mu);
85        mu
86    }
87}
88
89impl fmt::Debug for MuHasher {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        f.write_str("MuHasher(..)")
92    }
93}
94
95/// Defines a concrete FIPS 204 ML-DSA parameter set module and marker struct.
96macro_rules! define_ml_dsa_variant {
97    (
98        mod_name: $mod_name:ident,
99        struct_name: $struct_name:ident,
100        params_mod: $params_mod:ident,
101        doc_name: $doc_name:literal,
102        sec_cat: $sec_cat:literal
103    ) => {
104        /// Typed keys, signatures, and constants for
105        #[doc = concat!("**", $doc_name, "** (NIST Security Category ", $sec_cat, ").")]
106        pub mod $mod_name {
107            use super::*;
108            use crate::params::$params_mod as P;
109
110            /// Public verifying key size in bytes.
111            pub const PK_LEN: usize = P::PK_LEN;
112            /// Expanded private signing key size in bytes.
113            pub const SK_LEN: usize = P::SK_LEN;
114            /// Signature size in bytes.
115            pub const SIG_LEN: usize = P::SIG_LEN;
116            /// Key generation seed `xi` size in bytes (`32`).
117            pub const SEED_LEN: usize = crate::params::SEED_LEN;
118
119            /// Public verifying key for
120            #[doc = concat!($doc_name, ".")]
121            #[derive(Clone, Eq, PartialEq)]
122            pub struct VerifyingKey {
123                bytes: [u8; PK_LEN],
124            }
125
126            impl VerifyingKey {
127                /// Parses a verifying key from its exact byte encoding.
128                pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
129                    if bytes.len() != PK_LEN {
130                        return Err(Error::InvalidLength {
131                            expected: PK_LEN,
132                            actual: bytes.len(),
133                        });
134                    }
135                    let mut arr = [0u8; PK_LEN];
136                    arr.copy_from_slice(bytes);
137                    Ok(Self { bytes: arr })
138                }
139
140                /// Constructs a verifying key from a fixed-size byte array.
141                #[inline]
142                pub const fn from_array(bytes: [u8; PK_LEN]) -> Self {
143                    Self { bytes }
144                }
145
146                /// Returns the canonical byte representation of the verifying key.
147                #[inline]
148                pub const fn as_bytes(&self) -> &[u8; PK_LEN] {
149                    &self.bytes
150                }
151
152                /// Returns an all-zero placeholder verifying key for in-place initialization.
153                #[inline]
154                pub const fn zeroed() -> Self {
155                    Self {
156                        bytes: [0u8; PK_LEN],
157                    }
158                }
159
160                /// Returns the 64-byte FIPS 204 public key hash `tr = SHAKE256(pk, 64)`.
161                pub fn tr(&self) -> [u8; 64] {
162                    crate::mldsa::compute_tr(&self.bytes)
163                }
164
165                /// Creates a streaming [`MuHasher`] bound to this verifying key and `ctx`.
166                pub fn mu_hasher(&self, ctx: &[u8]) -> Result<MuHasher> {
167                    MuHasher::new(&self.tr(), ctx)
168                }
169
170                /// Verifies `sig` against a precomputed 64-byte External-mu representative `mu`.
171                pub fn verify_mu(&self, mu: &[u8; MU_LEN], sig: &Signature) -> Result<()> {
172                    crate::mldsa::verify_mu_internal::<
173                        { P::K },
174                        { P::L },
175                        { P::TAU },
176                        { P::BETA },
177                        { P::GAMMA1 },
178                        { P::GAMMA2 },
179                        { P::OMEGA },
180                        { P::C_TILDE_LEN },
181                        { P::W1_LEN },
182                        PK_LEN,
183                        SIG_LEN,
184                    >(&self.bytes, mu, &sig.bytes)
185                }
186
187                /// Verifies `sig` over `msg` and domain-separation context `ctx` (`|ctx| <= 255`).
188                pub fn verify(&self, msg: &[u8], ctx: &[u8], sig: &Signature) -> Result<()> {
189                    let tr = self.tr();
190                    let mu = crate::mldsa::compute_pure_mu(&tr, msg, ctx)?;
191                    crate::mldsa::verify_mu_internal::<
192                        { P::K },
193                        { P::L },
194                        { P::TAU },
195                        { P::BETA },
196                        { P::GAMMA1 },
197                        { P::GAMMA2 },
198                        { P::OMEGA },
199                        { P::C_TILDE_LEN },
200                        { P::W1_LEN },
201                        PK_LEN,
202                        SIG_LEN,
203                    >(&self.bytes, &mu, &sig.bytes)
204                }
205            }
206
207            impl fmt::Debug for VerifyingKey {
208                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209                    write!(f, "{}::VerifyingKey([{} bytes])", $doc_name, PK_LEN)
210                }
211            }
212
213            /// Private signing key for
214            #[doc = concat!($doc_name, " (automatically zeroized on drop, redacted in `Debug`).")]
215            pub struct SigningKey {
216                bytes: SecretBytes<SK_LEN>,
217            }
218
219            impl SigningKey {
220                /// Parses and validates an expanded FIPS 204 signing key.
221                ///
222                /// Validates that secret polynomial vectors `s1` and `s2` decode within `[−η, η]`.
223                pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
224                    if bytes.len() != SK_LEN {
225                        return Err(Error::InvalidLength {
226                            expected: SK_LEN,
227                            actual: bytes.len(),
228                        });
229                    }
230                    let mut arr = [0u8; SK_LEN];
231                    arr.copy_from_slice(bytes);
232                    let res =
233                        crate::mldsa::validate_sk::<{ P::K }, { P::L }, { P::ETA }, SK_LEN>(&arr);
234                    if let Err(e) = res {
235                        arr.zeroize();
236                        return Err(e);
237                    }
238                    let secret = SecretBytes::new(arr);
239                    arr.zeroize();
240                    Ok(Self { bytes: secret })
241                }
242
243                /// Exposes the raw expanded signing key bytes (handle with extreme care!).
244                #[inline]
245                pub fn expose_bytes(&self) -> &[u8; SK_LEN] {
246                    self.bytes.expose_secret()
247                }
248
249                /// Returns an all-zero placeholder signing key for in-place heap initialization
250                /// without stack-to-heap secret moves.
251                #[inline]
252                pub const fn zeroed() -> Self {
253                    Self {
254                        bytes: SecretBytes::new([0u8; SK_LEN]),
255                    }
256                }
257
258                /// Returns the 64-byte public key hash `tr` stored inside this signing key.
259                pub fn tr(&self) -> [u8; 64] {
260                    crate::mldsa::sk_tr(self.bytes.expose_secret())
261                }
262
263                /// Creates a streaming [`MuHasher`] bound to this signing key's public key hash `tr` and `ctx`.
264                pub fn mu_hasher(&self, ctx: &[u8]) -> Result<MuHasher> {
265                    MuHasher::new(&self.tr(), ctx)
266                }
267
268                /// Signs a precomputed 64-byte External-mu `mu` in hedged mode (fresh randomness).
269                pub fn sign_mu<R: CryptoRng + ?Sized>(
270                    &self,
271                    mu: &[u8; MU_LEN],
272                    rng: &mut R,
273                ) -> Result<Signature> {
274                    let mut rnd = SecretBytes::new([0u8; RND_LEN]);
275                    rng.try_fill_bytes(rnd.expose_secret_mut())?;
276                    sign_mu_raw(self, mu, rnd.expose_secret())
277                }
278
279                /// Signs a precomputed 64-byte External-mu `mu` in deterministic mode (`rnd = [0; 32]`).
280                pub fn sign_mu_deterministic(&self, mu: &[u8; MU_LEN]) -> Result<Signature> {
281                    let rnd = [0u8; RND_LEN];
282                    sign_mu_raw(self, mu, &rnd)
283                }
284
285                /// Signs `msg` with context `ctx` using fresh OS/CSPRNG randomness, writing the
286                /// signature directly into `sig_out` (`sig_out.len() == SIG_LEN`, FIPS 204
287                /// Algorithm 2) without allocating a `SIG_LEN`-byte signature copy on the stack.
288                pub fn sign_into<R: CryptoRng + ?Sized>(
289                    &self,
290                    msg: &[u8],
291                    ctx: &[u8],
292                    rng: &mut R,
293                    sig_out: &mut [u8],
294                ) -> Result<()> {
295                    let actual = sig_out.len();
296                    let out_arr: &mut [u8; SIG_LEN] =
297                        sig_out.try_into().map_err(|_| Error::InvalidLength {
298                            expected: SIG_LEN,
299                            actual,
300                        })?;
301                    let tr = self.tr();
302                    let mu = crate::mldsa::compute_pure_mu(&tr, msg, ctx)?;
303                    let mut rnd = SecretBytes::new([0u8; RND_LEN]);
304                    rng.try_fill_bytes(rnd.expose_secret_mut())?;
305                    crate::mldsa::sign_mu_internal_into::<
306                        { P::K },
307                        { P::L },
308                        { P::ETA },
309                        { P::TAU },
310                        { P::BETA },
311                        { P::GAMMA1 },
312                        { P::GAMMA2 },
313                        { P::OMEGA },
314                        { P::C_TILDE_LEN },
315                        { P::W1_LEN },
316                        SK_LEN,
317                        SIG_LEN,
318                    >(
319                        self.bytes.expose_secret(),
320                        &mu,
321                        rnd.expose_secret(),
322                        out_arr,
323                    )
324                }
325
326                /// Signs `msg` with context `ctx` using fresh OS/CSPRNG randomness (hedged mode,
327                /// FIPS 204 Algorithm 2).
328                pub fn sign<R: CryptoRng + ?Sized>(
329                    &self,
330                    msg: &[u8],
331                    ctx: &[u8],
332                    rng: &mut R,
333                ) -> Result<Signature> {
334                    let mut bytes = [0u8; SIG_LEN];
335                    self.sign_into(msg, ctx, rng, &mut bytes)?;
336                    Ok(Signature { bytes })
337                }
338
339                /// Signs `msg` with context `ctx` in deterministic mode (`rnd = [0; 32]`, FIPS 204).
340                pub fn sign_deterministic(&self, msg: &[u8], ctx: &[u8]) -> Result<Signature> {
341                    let rnd = [0u8; RND_LEN];
342                    let tr = self.tr();
343                    let mu = crate::mldsa::compute_pure_mu(&tr, msg, ctx)?;
344                    let bytes = crate::mldsa::sign_mu_internal::<
345                        { P::K },
346                        { P::L },
347                        { P::ETA },
348                        { P::TAU },
349                        { P::BETA },
350                        { P::GAMMA1 },
351                        { P::GAMMA2 },
352                        { P::OMEGA },
353                        { P::C_TILDE_LEN },
354                        { P::W1_LEN },
355                        SK_LEN,
356                        SIG_LEN,
357                    >(self.bytes.expose_secret(), &mu, &rnd)?;
358                    Ok(Signature { bytes })
359                }
360            }
361
362            impl Zeroize for SigningKey {
363                #[inline]
364                fn zeroize(&mut self) {
365                    self.bytes.zeroize();
366                }
367            }
368
369            impl fmt::Debug for SigningKey {
370                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371                    write!(f, "{}::SigningKey([REDACTED])", $doc_name)
372                }
373            }
374
375            /// Digital signature for
376            #[doc = concat!($doc_name, ".")]
377            #[derive(Clone, Eq, PartialEq)]
378            pub struct Signature {
379                bytes: [u8; SIG_LEN],
380            }
381
382            impl Signature {
383                /// Parses a signature from its exact byte encoding.
384                pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
385                    if bytes.len() != SIG_LEN {
386                        return Err(Error::InvalidLength {
387                            expected: SIG_LEN,
388                            actual: bytes.len(),
389                        });
390                    }
391                    let mut arr = [0u8; SIG_LEN];
392                    arr.copy_from_slice(bytes);
393                    Ok(Self { bytes: arr })
394                }
395
396                /// Constructs a signature from a fixed-size byte array.
397                #[inline]
398                pub const fn from_array(bytes: [u8; SIG_LEN]) -> Self {
399                    Self { bytes }
400                }
401
402                /// Returns the canonical byte representation of the signature.
403                #[inline]
404                pub const fn as_bytes(&self) -> &[u8; SIG_LEN] {
405                    &self.bytes
406                }
407            }
408
409            impl fmt::Debug for Signature {
410                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411                    write!(f, "{}::Signature([{} bytes])", $doc_name, SIG_LEN)
412                }
413            }
414
415            pub(crate) fn keygen_raw(xi: &[u8; SEED_LEN]) -> (VerifyingKey, SigningKey) {
416                let mut pair = (VerifyingKey::zeroed(), SigningKey::zeroed());
417                keygen_raw_into(xi, &mut pair.0, &mut pair.1);
418                pair
419            }
420
421            pub(crate) fn keygen_raw_into(
422                xi: &[u8; SEED_LEN],
423                vk_out: &mut VerifyingKey,
424                sk_out: &mut SigningKey,
425            ) {
426                crate::mldsa::keygen_internal_into::<
427                    { P::K },
428                    { P::L },
429                    { P::ETA },
430                    PK_LEN,
431                    SK_LEN,
432                >(xi, &mut vk_out.bytes, sk_out.bytes.expose_secret_mut());
433            }
434
435            pub(crate) fn sign_mu_raw(
436                sk: &SigningKey,
437                mu: &[u8; MU_LEN],
438                rnd: &[u8; RND_LEN],
439            ) -> Result<Signature> {
440                let bytes = crate::mldsa::sign_mu_internal::<
441                    { P::K },
442                    { P::L },
443                    { P::ETA },
444                    { P::TAU },
445                    { P::BETA },
446                    { P::GAMMA1 },
447                    { P::GAMMA2 },
448                    { P::OMEGA },
449                    { P::C_TILDE_LEN },
450                    { P::W1_LEN },
451                    SK_LEN,
452                    SIG_LEN,
453                >(sk.expose_bytes(), mu, rnd)?;
454                Ok(Signature { bytes })
455            }
456
457            /// Low-level deterministic and internal FIPS 204 interfaces for KAT testing and
458            /// RFC 9881 External-mu workflows (requires Cargo feature `hazmat`).
459            #[cfg(feature = "hazmat")]
460            pub mod hazmat {
461                use super::*;
462
463                /// FIPS 204 Algorithm 6: `ML-DSA.KeyGen_internal(xi)`.
464                pub fn keygen_internal(xi: &[u8; SEED_LEN]) -> (VerifyingKey, SigningKey) {
465                    keygen_raw(xi)
466                }
467
468                /// FIPS 204 Algorithm 7: `ML-DSA.Sign_internal(sk, M', rnd)`.
469                pub fn sign_internal(
470                    sk: &SigningKey,
471                    msg_prime: &[u8],
472                    rnd: &[u8; RND_LEN],
473                ) -> Result<Signature> {
474                    let tr = sk.tr();
475                    let mu = crate::mldsa::compute_internal_mu(&tr, msg_prime);
476                    sign_mu_internal(sk, &mu, rnd)
477                }
478
479                /// Signs a precomputed 64-byte `mu = SHAKE256(tr || M', 64)`
480                /// (RFC 9881 External-mu / streaming support).
481                pub fn sign_mu_internal(
482                    sk: &SigningKey,
483                    mu: &[u8; MU_LEN],
484                    rnd: &[u8; RND_LEN],
485                ) -> Result<Signature> {
486                    sign_mu_raw(sk, mu, rnd)
487                }
488
489                /// FIPS 204 Algorithm 8: `ML-DSA.Verify_internal(pk, M', sigma)`.
490                pub fn verify_internal(
491                    vk: &VerifyingKey,
492                    msg_prime: &[u8],
493                    sig: &Signature,
494                ) -> Result<()> {
495                    let tr = vk.tr();
496                    let mu = crate::mldsa::compute_internal_mu(&tr, msg_prime);
497                    verify_mu_internal(vk, &mu, sig)
498                }
499
500                /// Verifies a signature against a precomputed 64-byte `mu`.
501                pub fn verify_mu_internal(
502                    vk: &VerifyingKey,
503                    mu: &[u8; MU_LEN],
504                    sig: &Signature,
505                ) -> Result<()> {
506                    crate::mldsa::verify_mu_internal::<
507                        { P::K },
508                        { P::L },
509                        { P::TAU },
510                        { P::BETA },
511                        { P::GAMMA1 },
512                        { P::GAMMA2 },
513                        { P::OMEGA },
514                        { P::C_TILDE_LEN },
515                        { P::W1_LEN },
516                        PK_LEN,
517                        SIG_LEN,
518                    >(vk.as_bytes(), mu, sig.as_bytes())
519                }
520            }
521        }
522
523        /// Marker type implementing [`quantaegis_core::Signature`] for
524        #[doc = concat!("**", $doc_name, "** (NIST Security Category ", $sec_cat, ").")]
525        pub struct $struct_name;
526
527        impl $struct_name {
528            /// Derives a `(VerifyingKey, SigningKey)` keypair deterministically from a 32-byte
529            /// FIPS 204 seed `xi` (recommended format in RFC 9881).
530            ///
531            /// Note: returning `SigningKey` by value in safe Rust can leave an unzeroized copy in
532            /// the callee's return staging slot; FIPS/zeroization-critical callers should prefer
533            /// [`Self::keygen_into`] directly into caller-owned storage.
534            pub fn from_seed(
535                seed: &[u8; SEED_LEN],
536            ) -> ($mod_name::VerifyingKey, $mod_name::SigningKey) {
537                $mod_name::keygen_raw(seed)
538            }
539
540            /// Generates a fresh key pair directly into caller-owned storage and volatile-zeroizes
541            /// stack temporaries (`FIPS 204, Algorithm 1`).
542            pub fn keygen_into<R: CryptoRng + ?Sized>(
543                rng: &mut R,
544                vk_out: &mut $mod_name::VerifyingKey,
545                sk_out: &mut $mod_name::SigningKey,
546            ) -> Result<()> {
547                let mut xi = SecretBytes::new([0u8; SEED_LEN]);
548                rng.try_fill_bytes(xi.expose_secret_mut())?;
549                $mod_name::keygen_raw_into(xi.expose_secret(), vk_out, sk_out);
550                Ok(())
551            }
552
553            /// Signs `msg` with context `ctx` in deterministic mode (`rnd = [0; 32]`).
554            pub fn sign_deterministic(
555                sk: &$mod_name::SigningKey,
556                msg: &[u8],
557                ctx: &[u8],
558            ) -> Result<$mod_name::Signature> {
559                sk.sign_deterministic(msg, ctx)
560            }
561
562            /// Signs a precomputed 64-byte External-mu `mu` in hedged mode.
563            pub fn sign_mu<R: CryptoRng + ?Sized>(
564                sk: &$mod_name::SigningKey,
565                mu: &[u8; MU_LEN],
566                rng: &mut R,
567            ) -> Result<$mod_name::Signature> {
568                sk.sign_mu(mu, rng)
569            }
570
571            /// Signs a precomputed 64-byte External-mu `mu` in deterministic mode (`rnd = [0; 32]`).
572            pub fn sign_mu_deterministic(
573                sk: &$mod_name::SigningKey,
574                mu: &[u8; MU_LEN],
575            ) -> Result<$mod_name::Signature> {
576                sk.sign_mu_deterministic(mu)
577            }
578
579            /// Verifies `sig` against a precomputed 64-byte External-mu `mu`.
580            pub fn verify_mu(
581                vk: &$mod_name::VerifyingKey,
582                mu: &[u8; MU_LEN],
583                sig: &$mod_name::Signature,
584            ) -> Result<()> {
585                vk.verify_mu(mu, sig)
586            }
587        }
588
589        impl SignatureTrait for $struct_name {
590            type VerifyingKey = $mod_name::VerifyingKey;
591            type SigningKey = $mod_name::SigningKey;
592            type Sig = $mod_name::Signature;
593
594            /// Generates a fresh key pair by value; FIPS/zeroization-critical callers should prefer
595            /// [`Self::keygen_into`] to avoid safe-Rust return-slot staging copies.
596            fn keygen<R: CryptoRng + ?Sized>(
597                rng: &mut R,
598            ) -> Result<(Self::VerifyingKey, Self::SigningKey)> {
599                let mut res = Ok((
600                    $mod_name::VerifyingKey::zeroed(),
601                    $mod_name::SigningKey::zeroed(),
602                ));
603                if let Ok((ref mut vk, ref mut sk)) = res
604                    && let Err(e) = Self::keygen_into(rng, vk, sk)
605                {
606                    res = Err(e);
607                }
608                res
609            }
610
611            fn sign<R: CryptoRng + ?Sized>(
612                sk: &Self::SigningKey,
613                msg: &[u8],
614                ctx: &[u8],
615                rng: &mut R,
616            ) -> Result<Self::Sig> {
617                sk.sign(msg, ctx, rng)
618            }
619
620            fn verify(
621                vk: &Self::VerifyingKey,
622                msg: &[u8],
623                ctx: &[u8],
624                sig: &Self::Sig,
625            ) -> Result<()> {
626                vk.verify(msg, ctx, sig)
627            }
628        }
629    };
630}
631
632define_ml_dsa_variant! {
633    mod_name: ml_dsa_44,
634    struct_name: MlDsa44,
635    params_mod: p44,
636    doc_name: "ML-DSA-44",
637    sec_cat: "2"
638}
639
640define_ml_dsa_variant! {
641    mod_name: ml_dsa_65,
642    struct_name: MlDsa65,
643    params_mod: p65,
644    doc_name: "ML-DSA-65",
645    sec_cat: "3"
646}
647
648define_ml_dsa_variant! {
649    mod_name: ml_dsa_87,
650    struct_name: MlDsa87,
651    params_mod: p87,
652    doc_name: "ML-DSA-87",
653    sec_cat: "5"
654}
655
656#[cfg(test)]
657#[allow(clippy::expect_used)]
658mod streaming_mu_tests {
659    use super::*;
660
661    #[test]
662    fn streaming_mu_hasher_matches_oneshot_pure_ml_dsa() {
663        let seed = [0x42u8; SEED_LEN];
664        let (vk, sk) = MlDsa65::from_seed(&seed);
665        let msg = [0xABu8; 777];
666        let ctx = b"stream-ctx";
667
668        let mut signer_hasher = sk.mu_hasher(ctx).expect("valid ctx");
669        signer_hasher.update(&msg[..1]);
670        signer_hasher.update(&msg[1..137]);
671        signer_hasher.update(&msg[137..500]);
672        signer_hasher.update(&msg[500..]);
673        let signer_mu = signer_hasher.finalize();
674
675        let mut verifier_hasher = vk.mu_hasher(ctx).expect("valid ctx");
676        verifier_hasher.update(&msg[..333]);
677        verifier_hasher.update(&msg[333..]);
678        let verifier_mu = verifier_hasher.finalize();
679        assert_eq!(signer_mu, verifier_mu);
680
681        let sig_oneshot = MlDsa65::sign_deterministic(&sk, &msg, ctx).expect("oneshot sign");
682        let sig_mu = MlDsa65::sign_mu_deterministic(&sk, &signer_mu).expect("mu sign");
683        assert_eq!(sig_oneshot, sig_mu);
684
685        assert!(MlDsa65::verify(&vk, &msg, ctx, &sig_mu).is_ok());
686        assert!(MlDsa65::verify_mu(&vk, &verifier_mu, &sig_oneshot).is_ok());
687
688        let mut bad_mu = verifier_mu;
689        bad_mu[0] ^= 0x01;
690        assert_eq!(
691            MlDsa65::verify_mu(&vk, &bad_mu, &sig_oneshot),
692            Err(Error::InvalidSignature)
693        );
694        assert!(vk.mu_hasher(&[0u8; 256]).is_err());
695    }
696
697    #[test]
698    fn sign_rejects_overlong_context_before_consuming_rng() {
699        struct CountingFailRng {
700            calls: usize,
701        }
702
703        impl CryptoRng for CountingFailRng {
704            fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<()> {
705                self.calls += 1;
706                dest.fill(0xA5);
707                Err(Error::RngFailure)
708            }
709        }
710
711        let seed = [0x42u8; SEED_LEN];
712        let (_vk, sk) = MlDsa65::from_seed(&seed);
713        let mut rng = CountingFailRng { calls: 0 };
714        let res = sk.sign(b"msg", &[0u8; 256], &mut rng);
715        assert_eq!(
716            res,
717            Err(Error::ContextTooLong {
718                max: 255,
719                actual: 256,
720            })
721        );
722        assert_eq!(rng.calls, 0);
723    }
724}