Skip to main content

bouncycastle_mldsa/
mldsa.rs

1//! This page documents advanced features of the Module Lattice Digital Signature Algorithm (ML-DSA)
2//! available in this crate.
3//!
4//!
5//! # Streaming APIs
6//!
7//! Sometimes the message that needs to be signed or verified is too big to fit in device memory all at once.
8//! No worries, we got you covered!
9//!
10//! ```rust
11//! use bouncycastle_core::errors::SignatureError;
12//! use bouncycastle_core::traits::{Signer, SignatureVerifier};
13//! use bouncycastle_mldsa::{MLDSA65, MLDSATrait, MLDSAPublicKeyTrait, MuBuilder};
14//!
15//! let (pk, sk) = MLDSA65::keygen().unwrap();
16//!
17//! // For this example, assume that this message was so long that it is impractical to
18//! // stream the whole text over a network, and therefore it needs to be pre-hashed.
19//! let msg_chunk1 = b"The quick brown fox ";
20//! let msg_chunk2 = b"jumped over the lazy dog";
21//!
22//! let mut signer = MLDSA65::sign_init(&sk, None).unwrap();
23//! signer.sign_update(msg_chunk1);
24//! signer.sign_update(msg_chunk2);
25//! let sig = signer.sign_final().unwrap();
26//! // This is the signature value that can be saved to a file or whatever is needed.
27//!
28//! // This is compatible with a verifier that takes the whole message as one chunk:
29//! let msg = b"The quick brown fox jumped over the lazy dog";
30//! match MLDSA65::verify(&pk, msg, None, &sig) {
31//!     Ok(()) => println!("Signature is valid!"),
32//!     Err(SignatureError::SignatureVerificationFailed) => println!("Signature is invalid!"),
33//!     Err(e) => panic!("Something else went wrong: {:?}", e),
34//! }
35//!
36//! // There is also a streaming API for the verifier.
37//!
38//! let mut verifier = MLDSA65::verify_init(&pk, None).unwrap();
39//! verifier.verify_update(msg_chunk1);
40//! verifier.verify_update(msg_chunk2);
41//!
42//! match verifier.verify_final(&sig.as_slice()) {
43//!     Ok(()) => println!("Signature is valid!"),
44//!     Err(SignatureError::SignatureVerificationFailed) => println!("Signature is invalid!"),
45//!     Err(e) => panic!("Something else went wrong: {:?}", e),
46//! }
47//! ```
48//!
49//!
50//! Note that the streaming API also supports setting the signing context `ctx` and signing nonce `rnd`,
51//! which are explained in more detail below.
52//!
53//! ```rust
54//! use bouncycastle_core::errors::SignatureError;
55//! use bouncycastle_core::traits::{Signer, SignatureVerifier};
56//! use bouncycastle_mldsa::{MLDSA65, MLDSATrait, MLDSAPublicKeyTrait, MuBuilder};
57//!
58//! let (pk, sk) = MLDSA65::keygen().unwrap();
59//!
60//! // For this example, assume that this message was so long that it is impractical to
61//! // stream the whole text over a network, and therefore it needs to be pre-hashed.
62//! let msg_chunk1 = b"The quick brown fox ";
63//! let msg_chunk2 = b"jumped over the lazy dog";
64//!
65//! let mut signer = MLDSA65::sign_init(&sk, Some(b"signing ctx value")).unwrap();
66//! signer.set_signer_rnd([0u8; 32]); // an all-zero rnd is the "deterministic" mode of ML-DSA
67//! signer.sign_update(msg_chunk1);
68//! signer.sign_update(msg_chunk2);
69//! let sig = signer.sign_final().unwrap();
70//! ```
71//!
72//! # External Mu mode
73//!
74//! Here, `mu` refers to the message digest which is computed internally to the ML-DSA algorithm:
75//!
76//! > 𝜇 ← H(BytesToBits(𝑡𝑟)||𝑀′, 64)
77//! >   ▷ message representative that may optionally be computed in a different cryptographic module
78//!
79//! The External Mu mode of ML-DSA fulfills a similar function to [`hash_mldsa`] in that it allows large
80//! messages to be pre-digested outside of the cryptographic module that holds the private key,
81//! but it does it in a way that is compatible with the ML-DSA verification function.
82//! In other works, whereas [`hash_mldsa`] represents a different signature algorithm, the external mu
83//! mode of ML-DSA is simply internal implementation detail of how the signature was computed and
84//! produces signatures that are indistinguishable from "direct" ML-DSA mode.
85//!
86//! The one potential complication with external mu mode -- that [`hash_mldsa`] does not have --
87//! is that it requires the user to know the public key that they are about to sign the message with.
88//! Or, more specifically, the hash of the public key `tr`.
89//! `tr` is a public value (derivable from the public key), so there is no harm in, for example,
90//! sending it down to a client device so that it can pre-hash a large message and only send the
91//! 64-byte `mu` value up to the server to be signed.
92//! But in some contexts, the message has to be pre-hashed for performance reasons but
93//! the public key that will be used for signing cannot be known in advance.
94//! For those use cases, the only choice is to use [`hash_mldsa`].
95//!
96//! This library exposes [`MuBuilder`] which can be used to pre-hash a large to-be-signed message
97//! along with the public key hash `tr`:
98//!
99//! ```rust
100//! use bouncycastle_core::errors::SignatureError;
101//! use bouncycastle_mldsa::{MLDSA65, MLDSATrait, MLDSAPublicKeyTrait, MuBuilder};
102//! use bouncycastle_core::traits::{Signer, SignatureVerifier};
103//!
104//! let (pk, _) = MLDSA65::keygen().unwrap();
105//!
106//! // For this example, assume that this message was so long that it is impractical to
107//! // stream the whole text over a network, and therefore it needs to be pre-hashed.
108//! let msg = b"The quick brown fox jumped over the lazy dog";
109//!
110//! let mu: [u8; 64] = MuBuilder::compute_mu(&pk.compute_tr(), msg, None).unwrap();
111//! ```
112//!
113//! Note: in order to bind a `ctx` value (explained below), it is necessary to do in [`MuBuilder::compute_mu`].
114//!
115//! If the message really is so huge that it can't be hold it all in memory at once,
116//! then it might be preferable to use a streaming API for computing mu:
117//!
118//! ```rust
119//! use bouncycastle_core::errors::SignatureError;
120//! use bouncycastle_core::traits::{Signer, SignatureVerifier};
121//! use bouncycastle_mldsa::{MLDSA65, MLDSATrait, MLDSAPublicKeyTrait, MuBuilder};
122//!
123//! let (pk, _) = MLDSA65::keygen().unwrap();
124//!
125//! // For this example, assume that this message was so long that it is impractical to
126//! // stream the whole text over a network, and therefore it needs to be pre-hashed.
127//! let msg_chunk1 = b"The quick brown fox ";
128//! let msg_chunk2 = b"jumped over the lazy dog";
129//!
130//! let mut mb = MuBuilder::do_init(&pk.compute_tr(), None).unwrap();
131//! mb.do_update(msg_chunk1);
132//! mb.do_update(msg_chunk2);
133//! let mu = mb.do_final();
134//! ```
135//!
136//! Given a mu value, the user can compute a signature that verifies as normal (no mu's required!):
137//!
138//! ```rust
139//! use bouncycastle_core::errors::SignatureError;
140//! use bouncycastle_core::traits::{Signer, SignatureVerifier};
141//! use bouncycastle_mldsa::{MLDSA65, MLDSATrait, MLDSAPublicKeyTrait, MuBuilder};
142//!
143//! let msg = b"The quick brown fox jumped over the lazy dog";
144//!
145//! let (pk, sk) = MLDSA65::keygen().unwrap();
146//!
147//! // Assume this was computed somewhere else, then
148//! // the party that computed it would have had to know pk
149//! let mu: [u8; 64] = MuBuilder::compute_mu(&pk.compute_tr(), msg, None).unwrap();
150//!
151//! let sig = MLDSA65::sign_mu(&sk, None, &mu).unwrap();
152//! // This is the signature value that can be saved to a file or whatever it is needed.
153//!
154//! match MLDSA65::verify(&pk, msg, None, &sig) {
155//!     Ok(()) => println!("Signature is valid!"),
156//!     Err(SignatureError::SignatureVerificationFailed) => println!("Signature is invalid!"),
157//!     Err(e) => panic!("Something else went wrong: {:?}", e),
158//! }
159//!
160//! ```
161//!
162//! # Ctx and Rnd params
163//! Various functions in this crate let the user set the signing context value (`ctx`) and the signing nonce (`rnd`).
164//! Let's talk about them both:
165//!
166//! ## ctx
167//! The `ctx` value allows the signer to bind the signature value to an extra piece of information
168//! (up to 255 bytes long) that must also be known to the verifier in order to successfully verify the signature.
169//! This optional parameter allows cryptographic protocol designers to get additional binding properties
170//! from the ML-DSA signature.
171//! The `ctx` value should be something that is known to both the signer and verifier,
172//! does not necessarily need to be a secret, but should not go over the wire as part of the not-yet-verified message.
173//! Examples of uses of the `ctx` could include binding the application data type (ex: `FooEmailData`) in order
174//! to disambiguate other data types that share an encoding (ex: `FooTextDocumentData`) and might otherwise be possible for an
175//! attacker to trick a verifier into accepting one in place of the other.
176//! In a network protocol, `ctx` could be used to bind a transaction ID or protocol nonce in order to strongly
177//! protect against replay attacks.
178//! Generally, it is safe to ignore any property about a `ctx` object that is not well understood.
179//!
180//! Example of signing and verifying with a `ctx` value:
181//!
182//! ```rust
183//! use bouncycastle_core::errors::SignatureError;
184//! use bouncycastle_mldsa::{MLDSA65, MLDSATrait};
185//! use bouncycastle_core::traits::{Signer, SignatureVerifier};
186//!
187//! let msg = b"The quick brown fox";
188//! let ctx = b"FooTextDocumentFormat";
189//!
190//! let (pk, sk) = MLDSA65::keygen().unwrap();
191//!
192//! let sig = MLDSA65::sign(&sk, msg, Some(ctx)).unwrap();
193//! // This is the signature value that can be saved to a file or whatever it is needed.
194//!
195//! match MLDSA65::verify(&pk, msg, Some(ctx), &sig) {
196//!     Ok(()) => println!("Signature is valid!"),
197//!     Err(SignatureError::SignatureVerificationFailed) => println!("Signature is invalid!"),
198//!     Err(e) => panic!("Something else went wrong: {:?}", e),
199//! }
200//! ```
201//!
202//! ## rnd
203//!
204//! This is the signature nonce, whose purpose is to ensure that every time a signature is computed for the same
205//! message, it results in a different value
206//!
207//! In general, the "deterministic" mode of ML-DSA (which usually uses an all-zero `rnd`) is considered
208//! secure and safe to use, however, certain privacy properties may be lost. For example,
209//! it becomes evident that multiple identical signatures means that the same message was signed multiple times
210//! by the same private key.
211//!
212//! The default mode of ML-DSA uses a `rnd` generated by the library's OS-backed RNG, the `rnd` can be set by the user
213//! if necessary; for example if the function is run on an embedded device that does not have access to an RNG.
214//!
215//! Note that in order to avoid combinatorial explosion of API functions, setting the `rnd` value is only
216//! available in conjunction with external mu or streaming modes. The example of setting `rnd` on the streaming
217//! API was shown above.
218//!
219//! Here is an example of using the [`MLDSA::sign_mu_deterministic`] function:
220//!
221//! ```rust
222//! use bouncycastle_core::errors::SignatureError;
223//! use bouncycastle_core::traits::{Signer, SignatureVerifier};
224//! use bouncycastle_mldsa::{MLDSA65, MLDSATrait, MLDSAPublicKeyTrait, MuBuilder};
225//!
226//! let msg = b"The quick brown fox jumped over the lazy dog";
227//!
228//! let (pk, sk) = MLDSA65::keygen().unwrap();
229//!
230//! // Assume this was computed somewhere else, then
231//! // the party that computed it would have had to know pk
232//! let mu: [u8; 64] = MuBuilder::compute_mu(&pk.compute_tr(), msg, None).unwrap();
233//!
234//! // Typically, "deterministic" mode of ML-DSA will use an all-zero `rnd`,
235//! // but here it is exposed it so it can be set any value, as needed.
236//! let sig = MLDSA65::sign_mu_deterministic(&sk, None, &mu, [0u8; 32]).unwrap();
237//! // This is the signature value that can saved to a file or whatever it is needed.
238//!
239//! match MLDSA65::verify(&pk, msg, None, &sig) {
240//!     Ok(()) => println!("Signature is valid!"),
241//!     Err(SignatureError::SignatureVerificationFailed) => println!("Signature is invalid!"),
242//!     Err(e) => panic!("Something else went wrong: {:?}", e),
243//! }
244//! ```
245//!
246//! # Pre-expanding the public key for repeated use
247//!
248//! Within the usual ML-DSA public key representation, the public matrix A is stored as a seed rho, which
249//! means that both the ML-DSA.sign() and ML-DSA.verify() operations need to expand it into a full matrix
250//! before performing the matrix multiplication.
251//! The code contains a version of the public and private key structs that pre-expand the public matrix for repeated use.
252//!
253//! The runtime of ML-DSA.sign() is dominated by the rejection sampling look, making the A-expansion
254//! a negligible part of the function -- accounting for only about 2% of the computation.
255//! However, for ML-DSA.verify(), pre-expansion of the public matrix A gives speedups of 38% / 45% / 63%
256//! speedup for ML-DSA 44 / 65 / 87, especially if verifying multiple signatures against the same public key.
257//!
258//! ```rust
259//! use bouncycastle_mldsa::{MLDSA65, MLDSATrait};
260//! use bouncycastle_mldsa::{MLDSA65PublicKeyExpanded, MLDSA65PrivateKeyExpanded};
261//! use bouncycastle_core::traits::{Signer, SignatureVerifier};
262//! use bouncycastle_core::errors::SignatureError;
263//!
264//! let msg = b"The quick brown fox";
265//!
266//! let (pk, sk) = MLDSA65::keygen().unwrap();
267//!
268//! // The pre-expanded private key uses more memory, but has performance
269//! // improvements if doing multiple decapsulations with the same key
270//! // although the performance improvements on signing are slight -- only around 2%.
271//! let sk_expanded = MLDSA65PrivateKeyExpanded::from(&sk);
272//! let sig = MLDSA65::sign_with_expanded_key(&sk_expanded, msg, None).unwrap();
273//!
274//! // The pre-expand the public key uses more memory, but has performance
275//! // improvements if doing multiple encapsulations for the same key.
276//! let pk_expanded = MLDSA65PublicKeyExpanded::from(&pk);
277//! match MLDSA65::verify_with_expanded_key(&pk_expanded, msg, None, &sig) {
278//!     Ok(()) => println!("Signature is valid!"),
279//!     Err(SignatureError::SignatureVerificationFailed) => println!("Signature is invalid!"),
280//!     Err(e) => panic!("Something else went wrong: {:?}", e),
281//! }
282//! ```
283//!
284//! # sign_from_seed
285//!
286//! This mode is intended for users with extreme performance or resource-limitation requirements.
287//!
288//! A very careful analysis of the ML-DSA signing algorithm will show that
289//! the entire ML-DSA private key does not need to be in memory at the same time.
290//! In fact, it is possible to merge the keygen() and sign() functions
291//!
292//! The codebase contains [`MLDSA::sign_mu_deterministic_from_seed`] which implements such an algorithm.
293//! It has a significantly lower peak-memory-footprint than the regular signing API (although there's
294//! always room for more optimization), and according to our benchmarks it is only around 25% slower
295//! than signing with a fully-expanded private key -- which is still faster than performing a full
296//! keygen followed by a regular sign since there are intermediate values common to keygen and sign
297//! that the merged function is able to only compute once.
298//!
299//! Since this is intended for embedded systems specialists, the functions are not wrapped in
300//! the beginner-friendly APIs. It is implied that a user that needs this functionality also knows how
301//! to use it and what they are doing
302//!
303//! Example usage:
304//!
305//! ```rust
306//! use bouncycastle_core::errors::SignatureError;
307//! use bouncycastle_core::traits::{Signer, SignatureVerifier};
308//! use bouncycastle_core::key_material::{KeyMaterial256, KeyType, KeyMaterialTrait};
309//! use bouncycastle_hex as hex;
310//! use bouncycastle_mldsa::{MLDSA44, MLDSA44_SIG_LEN, MLDSATrait, MLDSAPublicKeyTrait, MuBuilder};
311//!
312//! let msg = b"The quick brown fox jumped over the lazy dog";
313//!
314//! let seed = KeyMaterial256::from_bytes_as_type(
315//!     &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(),
316//!     KeyType::Seed,
317//! ).unwrap();
318//!
319//! // The public key is computed so that the signature can be verified by anyone.
320//! // It also computes the hash `tr` of the public key to later be used to bind the public key at the time of signing.
321//! // There is no short-cut to efficiently computing the public key or `tr` from the seed;
322//! // The full keygen need to be run in order to get the full private key, at least momentarily, then
323//! // it can be discarded and only keep `tr` and `seed`.
324//! let (pk, _) = MLDSA44::keygen_from_seed(&seed).unwrap();
325//! let tr: [u8; 64] = pk.compute_tr();
326//!
327//! // Assume this was computed somewhere else, then
328//! // the party that computed it would have had to know pk
329//! let mu: [u8; 64] = MuBuilder::compute_mu(&tr, msg, None).unwrap();
330//! let rnd: [u8; 32] = [0u8; 32]; // with this API, the user is responsible for their own nonce
331//!                                // because in the cases where this level of memory optimization
332//!                                // is needed, our RNG probably won't work anyway.
333//!
334//! let mut sig = [0u8; MLDSA44_SIG_LEN];
335//! let bytes_written = MLDSA44::sign_mu_deterministic_from_seed_out(&seed, &mu, rnd, &mut sig)
336//!                                                                                 .unwrap();
337//!
338//! // it can be verified normally
339//! match MLDSA44::verify(&pk, msg, None, &sig) {
340//!     Ok(()) => println!("Signature is valid!"),
341//!     Err(SignatureError::SignatureVerificationFailed) => println!("Signature is invalid!"),
342//!     Err(e) => panic!("Something else went wrong: {:?}", e),
343//! }
344//! ```
345//!
346//! While this is currently only supported when operating from a seed-based private key, something analogous
347//! could be done that merges the sk_decode() and sign() routines when working with the standardized
348//! private key encoding (which is often called the "semi-expanded format" since the in-memory representation
349//! is still larger).
350//! Contact us if you need such a thing implemented.
351//!
352//!
353//! # Pre-expanding the public key for repeated use
354//!
355//! One of the computationally expensive parts of both ML-DSA.sign() and ML-DSA.verify() is expansion
356//! of the public matrix A from the public seed that is stored in with the compressed representation.
357//! When done as part of the keygen, expansion of the public matrix accounts for 20% - 30% of the keygen
358//! and verification time (depending on parameter set), and around 5% of the signing time since the
359//! rejection sampling loop dominates the runtime of the sign operation.
360//!
361//! If the key is loaded and used once for a single signature or a single verification,
362//! then there is no performance difference to whether the
363//! public matrix A is expanded as part of keygen or as part of sign / verify, but it does make both
364//! the public and private key take up more space in memory, so the default ML-DSA public and private key
365//! objects defer expansion until it is needed.
366//!
367//! However, in uses where many sign or verify operations are performed against the same
368//! key pair in quick succession, there can be substantial performance improvements to pre-computing
369//! this and holding on to a larger key object.
370//! This is accomplished via constructing a [`MLDSAPublicKeyExpanded`] or [`MLDSAPrivateKeyExpanded`] object
371//! of the appropriate parameter set from the original key, and then using this with [`MLDSA::sign_with_expanded_key`]
372//! or [`MLDSA::verify_with_expanded_key`].
373//! Both [`MLDSAPublicKeyExpanded`] and [`MLDSAPrivateKeyExpanded`] implement the same traits
374//! and therefore behave the same as their non-expanded counterparts in most regards.
375//!
376//! ```rust
377//! use bouncycastle_mldsa::{MLDSA65, MLDSATrait};
378//! use bouncycastle_mldsa::{MLDSA65PublicKeyExpanded, MLDSA65PrivateKeyExpanded};
379//! use bouncycastle_core::traits::{Signer, SignatureVerifier};
380//! use bouncycastle_core::errors::SignatureError;
381//!
382//! let msg = b"The quick brown fox jumped over the lazy dog";
383//!
384//! let (pk, sk) = MLDSA65::keygen().unwrap();
385//!
386//! // pre-expand the private key, which uses more memory, but has performance
387//! // improvements if doing multiple decapsulations with the same key
388//! let sk_expanded = MLDSA65PrivateKeyExpanded::from(&sk);
389//!
390//! let sig = MLDSA65::sign_with_expanded_key(&sk_expanded, msg, None).unwrap();
391//!
392//! // pre-expand the public key, which uses more memory, but has performance
393//! // improvements if doing multiple verifications with the same key
394//! let pk_expanded = MLDSA65PublicKeyExpanded::from(&pk);
395//!
396//! match MLDSA65::verify_with_expanded_key(&pk_expanded, msg, None, &sig) {
397//!     Ok(()) => println!("Signature is valid!"),
398//!     Err(SignatureError::SignatureVerificationFailed) => println!("Signature is invalid!"),
399//!     Err(e) => panic!("Something else went wrong: {:?}", e),
400//! }
401//! ```
402//!
403//! # Suspending and resuming execution via SerializableState
404//!
405//! When signing or verifying a large message, it can be advantageous to be able to suspend the operation
406//! to a cache and resume it later; for example if waiting for the message to stream over a slow network
407//! connection.
408//!
409//! This can bo accomplished for both the ML-DSA signer and verifier through the [`MuBuilder`] object.
410//!
411//! Suspending an in-progress sign operation:
412//!
413//! ```rust
414//! use bouncycastle_mldsa::{MLDSA65, MuBuilder, MLDSATrait, MLDSAPublicKeyTrait};
415//! use bouncycastle_core::traits::{Signer, Suspendable};
416//!
417//! let msg_part1 = b"The quick brown fox";
418//! let msg_part2 = b" jumped over the lazy dog";
419//!
420//! let (pk, sk) = MLDSA65::keygen().unwrap();
421//!
422//! let mut mb = MuBuilder::do_init(&pk.compute_tr(), None).unwrap();
423//! mb.do_update(msg_part1);
424//!
425//! // here, we'll suspend while "waiting" for the second part of the message
426//! let serialized_state = mb.suspend();
427//!
428//! // ...
429//! // do other things in the meantime
430//! // ...
431//!
432//! let mut mb_resumed = MuBuilder::from_suspended(serialized_state).unwrap();
433//! mb_resumed.do_update(msg_part2);
434//! let mu: [u8; 64] = mb_resumed.do_final();
435//!
436//! // Now we'll do the actual sign_mu operation
437//! let sig = MLDSA65::sign_mu(&sk, None, &mu).unwrap();
438//! ```
439//!
440//! Suspending an in-progress verify operation behaves exactly the same way:
441//!
442//! ```rust
443//! use bouncycastle_mldsa::{MLDSA65, MuBuilder, MLDSATrait, MLDSAPublicKeyTrait};
444//! use bouncycastle_core::traits::{Signer, Suspendable};
445//! use bouncycastle_core::errors::SignatureError;
446//!
447//! let (pk, sk) = MLDSA65::keygen().unwrap();
448//!
449//! // first, let's generate a signature to verify
450//! let sig = MLDSA65::sign(&sk, b"The quick brown fox jumped over the lazy dog", None).unwrap();
451//!
452//! // Now we'll verify it with a suspension in the middle
453//! let msg_part1 = b"The quick brown fox";
454//! let msg_part2 = b" jumped over the lazy dog";
455//!
456//! let mut mb = MuBuilder::do_init(&pk.compute_tr(), None).unwrap();
457//! mb.do_update(msg_part1);
458//!
459//! // here, we'll suspend while "waiting" for the second part of the message
460//! let serialized_state = mb.suspend();
461//!
462//! // ...
463//! // do other things in the meantime
464//! // ...
465//!
466//! let mut mb_resumed = MuBuilder::from_suspended(serialized_state).unwrap();
467//! mb_resumed.do_update(msg_part2);
468//! let mu: [u8; 64] = mb_resumed.do_final();
469//!
470//! // Now we'll do the actual verify_mu operation
471//! match MLDSA65::verify_mu(&pk, Some(&pk.A_hat()), &mu, &sig) {
472//!     Ok(()) => println!("Signature is valid!"),
473//!     Err(SignatureError::SignatureVerificationFailed) => println!("Signature is invalid!"),
474//!     Err(e) => panic!("Something else went wrong: {:?}", e),
475//! }
476//! ```
477
478use crate::aux_functions::{
479    expand_mask, expandA, expandS, make_hint_vecs, power_2_round_vec, sample_in_ball, sig_decode,
480    sig_encode, use_hint_vecs,
481};
482use crate::matrix::{Matrix, Vector};
483use crate::mldsa_keys::{MLDSAPrivateKeyInternalTrait, MLDSAPrivateKeyTrait};
484use crate::mldsa_keys::{MLDSAPublicKeyInternalTrait, MLDSAPublicKeyTrait};
485use crate::{
486    MLDSA44PrivateKey, MLDSA44PublicKey, MLDSA65PrivateKey, MLDSA65PublicKey, MLDSA87PrivateKey,
487    MLDSA87PublicKey, MLDSAPrivateKeyExpanded, MLDSAPublicKeyExpanded,
488};
489use bouncycastle_core::errors::{RNGError, SignatureError, SuspendableError};
490use bouncycastle_core::key_material::{KeyMaterial, KeyMaterial256, KeyMaterialTrait, KeyType};
491use bouncycastle_core::traits::{
492    Algorithm, AlgorithmOID, RNG, SecurityStrength, SignatureVerifier, Signer, Suspendable, XOF,
493};
494use bouncycastle_rng::HashDRBG_SHA512;
495use bouncycastle_sha3::{SHAKE128, SHAKE256, SUSPENDED_SHA3_STATE_LEN};
496use bouncycastle_utils::secret::Secret;
497use core::marker::PhantomData;
498
499// imports needed just for docs
500#[allow(unused_imports)]
501use crate::hash_mldsa;
502#[allow(unused_imports)]
503use bouncycastle_core::traits::{PHSignatureVerifier, PHSigner};
504
505/*** Constants ***/
506
507///
508pub const ML_DSA_44_NAME: &str = "ML-DSA-44";
509///
510pub const ML_DSA_65_NAME: &str = "ML-DSA-65";
511///
512pub const ML_DSA_87_NAME: &str = "ML-DSA-87";
513
514// From FIPS 204 Table 1 and Table 2
515
516// Constants that are the same for all parameter sets
517pub(crate) const N: usize = 256;
518pub(crate) const q: i32 = 8380417;
519pub(crate) const q_inv: i32 = 58728449; // q ^ (-1) mod 2 ^32
520pub(crate) const d: i32 = 13;
521/// Length of the \[u8] holding an ML-DSA seed value.
522pub const MLDSA_SEED_LEN: usize = 32;
523/// Length of the \[u8] holding an ML-DSA signing random value.
524pub const MLDSA_RND_LEN: usize = 32;
525/// Length of the \[u8] holding an ML-DSA tr value (which is the SHAKE256 hash of the public key).
526pub const MLDSA_TR_LEN: usize = 64;
527/// Length of the \[u8] holding an ML-DSA mu value.
528pub const MLDSA_MU_LEN: usize = 64;
529pub(crate) const POLY_T0PACKED_LEN: usize = 416;
530pub(crate) const POLY_T1PACKED_LEN: usize = 320;
531
532/* ML-DSA-44 params */
533
534/// Length of the \[u8] holding a ML-DSA-44 public key.
535pub const MLDSA44_PK_LEN: usize = 1312;
536/// Length of the \[u8] holding a ML-DSA-44 private key.
537pub const MLDSA44_SK_LEN: usize = 2560;
538/// Length of the \[u8] holding a ML-DSA-44 signature value.
539pub const MLDSA44_SIG_LEN: usize = 2420;
540pub(crate) const MLDSA44_TAU: i32 = 39;
541pub(crate) const MLDSA44_LAMBDA: i32 = 128;
542pub(crate) const MLDSA44_GAMMA1: i32 = 1 << 17;
543pub(crate) const MLDSA44_GAMMA2: i32 = (q - 1) / 88; // mutants note: because of the bitshifting, the "- 1" ends up not mattering
544pub(crate) const MLDSA44_k: usize = 4;
545pub(crate) const MLDSA44_l: usize = 4;
546pub(crate) const MLDSA44_ETA: usize = 2;
547pub(crate) const MLDSA44_BETA: i32 = 78;
548pub(crate) const MLDSA44_OMEGA: i32 = 80;
549
550// Useful derived values
551pub(crate) const MLDSA44_C_TILDE: usize = 32;
552pub(crate) const MLDSA44_POLY_Z_PACKED_LEN: usize = 576;
553pub(crate) const MLDSA44_POLY_W1_PACKED_LEN: usize = 192;
554pub(crate) const MLDSA44_LAMBDA_over_4: usize = 128 / 4;
555pub(crate) const MLDSA44_GAMMA1_MINUS_BETA: i32 = MLDSA44_GAMMA1 - MLDSA44_BETA;
556pub(crate) const MLDSA44_GAMMA2_MINUS_BETA: i32 = MLDSA44_GAMMA2 - MLDSA44_BETA;
557
558// Alg 32
559// 1: 𝑐 ← 1 + bitlen (𝛾1 − 1)
560pub(crate) const MLDSA44_GAMMA1_MASK_LEN: usize = 576; // 32*(1 + bitlen (𝛾1 − 1) )
561
562/* ML-DSA-65 params */
563
564/// Length of the \[u8] holding a ML-DSA-65 public key.
565pub const MLDSA65_PK_LEN: usize = 1952;
566/// Length of the \[u8] holding a ML-DSA-65 private key.
567pub const MLDSA65_SK_LEN: usize = 4032;
568/// Length of the \[u8] holding a ML-DSA-65 signature value.
569pub const MLDSA65_SIG_LEN: usize = 3309;
570pub(crate) const MLDSA65_TAU: i32 = 49;
571pub(crate) const MLDSA65_LAMBDA: i32 = 192;
572pub(crate) const MLDSA65_GAMMA1: i32 = 1 << 19;
573pub(crate) const MLDSA65_GAMMA2: i32 = (q - 1) / 32; // mutants note: because of the bitshifting, the "- 1" ends up not mattering
574pub(crate) const MLDSA65_k: usize = 6;
575pub(crate) const MLDSA65_l: usize = 5;
576pub(crate) const MLDSA65_ETA: usize = 4;
577pub(crate) const MLDSA65_BETA: i32 = 196;
578pub(crate) const MLDSA65_OMEGA: i32 = 55;
579
580// Useful derived values
581pub(crate) const MLDSA65_C_TILDE: usize = 48;
582pub(crate) const MLDSA65_POLY_Z_PACKED_LEN: usize = 640;
583pub(crate) const MLDSA65_POLY_W1_PACKED_LEN: usize = 128;
584pub(crate) const MLDSA65_LAMBDA_over_4: usize = 192 / 4;
585pub(crate) const MLDSA65_GAMMA1_MINUS_BETA: i32 = MLDSA65_GAMMA1 - MLDSA65_BETA;
586pub(crate) const MLDSA65_GAMMA2_MINUS_BETA: i32 = MLDSA65_GAMMA2 - MLDSA65_BETA;
587
588// Alg 32
589// 1: 𝑐 ← 1 + bitlen (𝛾1 − 1)
590pub(crate) const MLDSA65_GAMMA1_MASK_LEN: usize = 640;
591
592/* ML-DSA-87 params */
593
594/// Length of the \[u8] holding a ML-DSA-87 public key.
595pub const MLDSA87_PK_LEN: usize = 2592;
596/// Length of the \[u8] holding a ML-DSA-87 private key.
597pub const MLDSA87_SK_LEN: usize = 4896;
598/// Length of the \[u8] holding a ML-DSA-87 signature value.
599pub const MLDSA87_SIG_LEN: usize = 4627;
600pub(crate) const MLDSA87_TAU: i32 = 60;
601pub(crate) const MLDSA87_LAMBDA: i32 = 256;
602pub(crate) const MLDSA87_GAMMA1: i32 = 1 << 19;
603pub(crate) const MLDSA87_GAMMA2: i32 = (q - 1) / 32; // mutants note: because of the bitshifting, the "- 1" ends up not mattering
604pub(crate) const MLDSA87_k: usize = 8;
605pub(crate) const MLDSA87_l: usize = 7;
606pub(crate) const MLDSA87_ETA: usize = 2;
607pub(crate) const MLDSA87_BETA: i32 = 120;
608pub(crate) const MLDSA87_OMEGA: i32 = 75;
609
610// Useful derived values
611pub(crate) const MLDSA87_C_TILDE: usize = 64;
612pub(crate) const MLDSA87_POLY_Z_PACKED_LEN: usize = 640;
613pub(crate) const MLDSA87_POLY_W1_PACKED_LEN: usize = 128;
614pub(crate) const MLDSA87_LAMBDA_over_4: usize = 256 / 4;
615pub(crate) const MLDSA87_GAMMA1_MINUS_BETA: i32 = MLDSA87_GAMMA1 - MLDSA87_BETA;
616pub(crate) const MLDSA87_GAMMA2_MINUS_BETA: i32 = MLDSA87_GAMMA2 - MLDSA87_BETA;
617
618// Alg 32
619// 1: 𝑐 ← 1 + bitlen (𝛾1 − 1)
620pub(crate) const MLDSA87_GAMMA1_MASK_LEN: usize = 640;
621
622// Typedefs just to make the algorithms look more like the FIPS 204 sample code.
623pub(crate) type H = SHAKE256;
624pub(crate) type G = SHAKE128;
625
626/*** Pub Types ***/
627
628/// The ML-DSA-44 algorithm.
629pub type MLDSA44 = MLDSA<
630    MLDSA44_PK_LEN,
631    MLDSA44_SK_LEN,
632    MLDSA44_SIG_LEN,
633    MLDSA44PublicKey,
634    MLDSA44PrivateKey,
635    MLDSA44_TAU,
636    MLDSA44_LAMBDA,
637    MLDSA44_GAMMA1,
638    MLDSA44_GAMMA2,
639    MLDSA44_k,
640    MLDSA44_l,
641    MLDSA44_ETA,
642    MLDSA44_BETA,
643    MLDSA44_OMEGA,
644    MLDSA44_C_TILDE,
645    MLDSA44_POLY_Z_PACKED_LEN,
646    MLDSA44_POLY_W1_PACKED_LEN,
647    MLDSA44_LAMBDA_over_4,
648    MLDSA44_GAMMA1_MINUS_BETA,
649    MLDSA44_GAMMA2_MINUS_BETA,
650    MLDSA44_GAMMA1_MASK_LEN,
651>;
652
653impl Algorithm for MLDSA44 {
654    const ALG_NAME: &'static str = ML_DSA_44_NAME;
655    const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit;
656}
657/// Assigned by NIST in the Computer Security Objects Register: id-ml-dsa-44 { sigAlgs 17 }
658impl AlgorithmOID for MLDSA44 {
659    const OID: &'static [u32] = &[2, 16, 840, 1, 101, 3, 4, 3, 17];
660    const OID_DER: &'static [u8] =
661        &[0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x11];
662}
663
664/// The ML-DSA-65 algorithm.
665pub type MLDSA65 = MLDSA<
666    MLDSA65_PK_LEN,
667    MLDSA65_SK_LEN,
668    MLDSA65_SIG_LEN,
669    MLDSA65PublicKey,
670    MLDSA65PrivateKey,
671    MLDSA65_TAU,
672    MLDSA65_LAMBDA,
673    MLDSA65_GAMMA1,
674    MLDSA65_GAMMA2,
675    MLDSA65_k,
676    MLDSA65_l,
677    MLDSA65_ETA,
678    MLDSA65_BETA,
679    MLDSA65_OMEGA,
680    MLDSA65_C_TILDE,
681    MLDSA65_POLY_Z_PACKED_LEN,
682    MLDSA65_POLY_W1_PACKED_LEN,
683    MLDSA65_LAMBDA_over_4,
684    MLDSA65_GAMMA1_MINUS_BETA,
685    MLDSA65_GAMMA2_MINUS_BETA,
686    MLDSA65_GAMMA1_MASK_LEN,
687>;
688
689impl Algorithm for MLDSA65 {
690    const ALG_NAME: &'static str = ML_DSA_65_NAME;
691    const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_192bit;
692}
693/// Assigned by NIST in the Computer Security Objects Register: id-ml-dsa-65 { sigAlgs 18 }
694impl AlgorithmOID for MLDSA65 {
695    const OID: &'static [u32] = &[2, 16, 840, 1, 101, 3, 4, 3, 18];
696    const OID_DER: &'static [u8] =
697        &[0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x12];
698}
699
700/// The ML-DSA-87 algorithm.
701pub type MLDSA87 = MLDSA<
702    MLDSA87_PK_LEN,
703    MLDSA87_SK_LEN,
704    MLDSA87_SIG_LEN,
705    MLDSA87PublicKey,
706    MLDSA87PrivateKey,
707    MLDSA87_TAU,
708    MLDSA87_LAMBDA,
709    MLDSA87_GAMMA1,
710    MLDSA87_GAMMA2,
711    MLDSA87_k,
712    MLDSA87_l,
713    MLDSA87_ETA,
714    MLDSA87_BETA,
715    MLDSA87_OMEGA,
716    MLDSA87_C_TILDE,
717    MLDSA87_POLY_Z_PACKED_LEN,
718    MLDSA87_POLY_W1_PACKED_LEN,
719    MLDSA87_LAMBDA_over_4,
720    MLDSA87_GAMMA1_MINUS_BETA,
721    MLDSA87_GAMMA2_MINUS_BETA,
722    MLDSA87_GAMMA1_MASK_LEN,
723>;
724
725impl Algorithm for MLDSA87 {
726    const ALG_NAME: &'static str = ML_DSA_87_NAME;
727    const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_256bit;
728}
729/// Assigned by NIST in the Computer Security Objects Register: id-ml-dsa-87 { sigAlgs 19 }
730impl AlgorithmOID for MLDSA87 {
731    const OID: &'static [u32] = &[2, 16, 840, 1, 101, 3, 4, 3, 19];
732    const OID_DER: &'static [u8] =
733        &[0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x13];
734}
735
736/// The core internal implementation of the ML-DSA algorithm.
737/// This needs to be public for the compiler to be able to find it,
738/// but it shouldn't ever need to be used directly.
739/// Please use the named public types [`MLDSA44`], [`MLDSA65`], [`MLDSA87`] instead.
740pub struct MLDSA<
741    const PK_LEN: usize,
742    const SK_LEN: usize,
743    const SIG_LEN: usize,
744    PK: MLDSAPublicKeyTrait<k, l, PK_LEN> + MLDSAPublicKeyInternalTrait<k, PK_LEN>,
745    SK: MLDSAPrivateKeyTrait<k, l, ETA, SK_LEN, PK_LEN>
746        + MLDSAPrivateKeyInternalTrait<k, l, ETA, SK_LEN, PK_LEN>,
747    const TAU: i32,
748    const LAMBDA: i32,
749    const GAMMA1: i32,
750    const GAMMA2: i32,
751    const k: usize,
752    const l: usize,
753    const ETA: usize,
754    const BETA: i32,
755    const OMEGA: i32,
756    const C_TILDE: usize,
757    const POLY_VEC_H_PACKED_LEN: usize,
758    const POLY_W1_PACKED_LEN: usize,
759    const LAMBDA_over_4: usize,
760    const GAMMA1_MINUS_BETA: i32,
761    const GAMMA2_MINUS_BETA: i32,
762    const GAMMA1_MASK_LEN: usize,
763> {
764    _phantom: PhantomData<(PK, SK)>,
765
766    /// used for streaming the message for both signing and verifying
767    mu_builder: MuBuilder,
768
769    signer_rnd: Option<[u8; MLDSA_RND_LEN]>,
770
771    /// only used in streaming sign operations
772    sk: Option<SK>,
773
774    /// only used in streaming sign operations instead of sk
775    seed: Option<KeyMaterial<32>>,
776
777    /// only used in streaming verify operations
778    pk: Option<PK>,
779}
780
781impl<
782    const PK_LEN: usize,
783    const SK_LEN: usize,
784    const SIG_LEN: usize,
785    PK: MLDSAPublicKeyTrait<k, l, PK_LEN> + MLDSAPublicKeyInternalTrait<k, PK_LEN>,
786    SK: MLDSAPrivateKeyTrait<k, l, ETA, SK_LEN, PK_LEN>
787        + MLDSAPrivateKeyInternalTrait<k, l, ETA, SK_LEN, PK_LEN>,
788    const TAU: i32,
789    const LAMBDA: i32,
790    const GAMMA1: i32,
791    const GAMMA2: i32,
792    const k: usize,
793    const l: usize,
794    const ETA: usize,
795    const BETA: i32,
796    const OMEGA: i32,
797    const C_TILDE: usize,
798    const POLY_Z_PACKED_LEN: usize,
799    const POLY_W1_PACKED_LEN: usize,
800    const LAMBDA_over_4: usize,
801    const GAMMA1_MINUS_BETA: i32,
802    const GAMMA2_MINUS_BETA: i32,
803    const GAMMA1_MASK_LEN: usize,
804>
805    MLDSA<
806        PK_LEN,
807        SK_LEN,
808        SIG_LEN,
809        PK,
810        SK,
811        TAU,
812        LAMBDA,
813        GAMMA1,
814        GAMMA2,
815        k,
816        l,
817        ETA,
818        BETA,
819        OMEGA,
820        C_TILDE,
821        POLY_Z_PACKED_LEN,
822        POLY_W1_PACKED_LEN,
823        LAMBDA_over_4,
824        GAMMA1_MINUS_BETA,
825        GAMMA2_MINUS_BETA,
826        GAMMA1_MASK_LEN,
827    >
828{
829    /// Implements Algorithm 6 of FIPS 204
830    /// Note: NIST has made a special exception in the FIPS 204 FAQ that this _internal function
831    /// may in fact be exposed outside the crypto module.
832    ///
833    /// Unlike other interfaces across the library that take an &impl KeyMaterial, this one
834    /// specifically takes a 32-byte [`KeyMaterial256`] and checks that it has [`KeyType::Seed`] and
835    /// [`SecurityStrength::_256bit`].
836    /// If you happen to have your seed in a larger KeyMaterial, you'll have to copy it into a
837    /// correctly-sized [`KeyMaterial256`] using [`KeyMaterialTrait::truncate`].
838    pub(crate) fn keygen_internal(seed: &KeyMaterial256) -> Result<(PK, SK), SignatureError> {
839        if !(seed.key_type() == KeyType::Seed || seed.key_type() == KeyType::CryptographicRandom)
840            || seed.key_len() != 32
841        {
842            return Err(SignatureError::KeyGenError(
843                "Seed must be 32 bytes and KeyType::Seed or KeyType::BytesFullEntropy.",
844            ));
845        }
846
847        if seed.security_strength() < SecurityStrength::from_bits(LAMBDA as usize) {
848            return Err(SignatureError::KeyGenError(
849                "Seed SecurityStrength must match algorithm security strength",
850            ));
851        }
852
853        // Alg 6 line 1: (rho, rho_prime, K) <- H(𝜉||IntegerToBytes(𝑘, 1)||IntegerToBytes(ℓ, 1), 128)
854        //   ▷ expand seed
855        let mut rho: [u8; 32] = [0u8; 32];
856        let mut K = Secret::<[u8; 32]>::new();
857
858        let (s1_hat, mut s2) = {
859            // scope for h
860            let mut h = H::default();
861            h.absorb(seed.ref_to_bytes()).expect("absorb before squeeze is infallible");
862            h.absorb(&(k as u8).to_le_bytes()).expect("absorb before squeeze is infallible");
863            h.absorb(&(l as u8).to_le_bytes()).expect("absorb before squeeze is infallible");
864            let bytes_written = h.squeeze_out(&mut rho);
865            debug_assert_eq!(bytes_written, 32);
866            let mut rho_prime: [u8; 64] = [0u8; 64];
867            let bytes_written = h.squeeze_out(&mut rho_prime);
868            debug_assert_eq!(bytes_written, 64);
869            let bytes_written = h.squeeze_out(&mut *K);
870            debug_assert_eq!(bytes_written, 32);
871
872            // 4: (𝐬1, 𝐬2) ← ExpandS(𝜌′)
873            let (mut s1, s2) = expandS::<k, l, ETA>(&rho_prime);
874
875            s1.ntt();
876            (s1, s2)
877        };
878
879        let t_hat = {
880            // scope for s1_hat
881            // 3: 𝐀_hat ← ExpandA(𝜌) ▷ 𝐀 is generated and stored in NTT representation as 𝐀
882            let A_hat = expandA::<k, l>(&rho);
883
884            // 5: 𝐭 ← NTT−1(𝐀 ∘ NTT(𝐬1)) + 𝐬2
885            //   ▷ compute 𝐭 = 𝐀𝐬1 + 𝐬2
886            A_hat.matrix_vector_ntt(&s1_hat)
887        };
888
889        let (t1, mut t0) = {
890            // scope for t
891            let mut t = t_hat;
892            t.inv_ntt();
893            t.add_vector_ntt(&s2);
894            t.conditional_add_q();
895
896            // 6: (𝐭1, 𝐭0) ← Power2Round(𝐭)
897            //   ▷ compress 𝐭
898            //   ▷ PowerTwoRound is applied componentwise (see explanatory text in Section 7.4)
899            power_2_round_vec::<k>(&t)
900        };
901
902        // 8: 𝑝𝑘 ← pkEncode(𝜌, 𝐭1)
903        let pk = PK::new(rho, t1);
904
905        // 9: 𝑡𝑟 ← H(𝑝𝑘, 64)
906        let tr = pk.compute_tr();
907
908        // 10: 𝑠𝑘 ← skEncode(𝜌, 𝐾, 𝑡𝑟, 𝐬1, 𝐬2, 𝐭0)
909        //   ▷ 𝐾 and 𝑡𝑟 are for use in signing
910        // Deviation from the FIPS:
911        //   Hold on to s1, s2, t0 in ntt form
912        //   Note: the result here is not necessarily in reduced form, but since .reduce() is expensive,
913        //   it is saved for the encode() operation since that is the only place where it matters
914        //   to have them in normalized form.
915        s2.ntt();
916        t0.ntt();
917        // let sk = SK::new(&rho, &K, &tr, &s1_hat, &s2, &t0, Some(seed.clone()));
918        let sk = SK::new(rho, K, tr, s1_hat, s2, t0, Some(seed.clone()));
919
920        // tr is public data, does not need to be zeroized
921        // s1, s2, t0 are all Vectors of Polynomials, so implement a zeroizing Drop
922
923        // 11: return (𝑝𝑘, 𝑠𝑘)
924        Ok((pk, sk))
925    }
926
927    /// Algorithm 7 ML-DSA.Sign_internal(𝑠𝑘, 𝑀′, 𝑟𝑛𝑑)
928    /// modified to take an externally-computed mu instead of M', and to take the public matrix A_hat
929    fn sign_internal(
930        sk: &SK,
931        A_hat: &Matrix<k, l>,
932        mu: &[u8; 64],
933        rnd: [u8; 32],
934        output: &mut [u8; SIG_LEN],
935    ) -> Result<usize, SignatureError> {
936        output.fill(0);
937
938        // 1: (𝜌, 𝐾, 𝑡𝑟, 𝐬1, 𝐬2, 𝐭0) ← skDecode(𝑠𝑘)
939        // 2: 𝐬1̂_hat ← NTT(𝐬1)
940        // 3: 𝐬2̂_hat ← NTT(𝐬2)
941        // 4: 𝐭0̂_hat ← NTT(𝐭0)̂
942        // Already done -- the sk struct is already decoded and in NTT form
943
944        // 5: 𝐀_hat ← ExpandA(𝜌)
945        // It does an optimization where the user can pre-expand A_hat within the
946        // public key object for faster repeated encapsulations against this public key.
947
948        // 6: 𝜇 ← H(BytesToBits(𝑡𝑟)||𝑀 ′, 64)
949        // skip: mu has already been provided
950
951        let mut rho_p_p: [u8; 64] = {
952            // scope for h
953            // 7: 𝜌″ ← H(𝐾||𝑟𝑛𝑑||𝜇, 64)
954            let mut h = H::new();
955            h.absorb(&**sk.K()).expect("absorb before squeeze is infallible");
956            h.absorb(&rnd).expect("absorb before squeeze is infallible");
957            h.absorb(mu).expect("absorb before squeeze is infallible");
958            let mut rho_p_p = [0u8; 64];
959            h.squeeze_out(&mut rho_p_p);
960
961            rho_p_p
962        };
963
964        // 8: 𝜅 ← 0
965        //  ▷ initialize counter 𝜅
966        let mut kappa: u16 = 0;
967
968        // 9: (𝐳, 𝐡) ← ⊥
969        // handled in the loop
970
971        // 10: while (𝐳, 𝐡) = ⊥ do
972        //  ▷ rejection sampling loop
973
974        // these need to be outside the loop because they form the encoded signature value
975        let mut sig_val_c_tilde = [0u8; LAMBDA_over_4];
976        let mut sig_val_z: Vector<l>;
977        let mut sig_val_h: Vector<k>;
978        loop {
979            // FIPS 204 s. 6.2 allows:
980            //   "Implementations may limit the number of iterations in this loop to not exceed a finite maximum value."
981            // mutants note: there is no test for this because, at this point,
982            // we don't know of a KAT that will exceed this limit.
983            if kappa > 1000 * k as u16 {
984                return Err(SignatureError::GenericError(
985                    "Rejection sampling loop exceeded max iterations, try again with a different signing nonce.",
986                ));
987            }
988
989            // 11: 𝐲 ∈ 𝑅^ℓ ← ExpandMask(𝜌″, 𝜅)
990            let mut y = expand_mask::<l, GAMMA1, GAMMA1_MASK_LEN>(&rho_p_p, kappa);
991
992            let w = {
993                // scope for y_hat
994                // 12: 𝐰 ← NTT−1(𝐀_hat * NTT(𝐲))
995                let mut y_hat = y.clone();
996                y_hat.ntt();
997                let mut w = A_hat.matrix_vector_ntt(&y_hat);
998                w.inv_ntt();
999                w.conditional_add_q();
1000                w
1001            };
1002
1003            // 13: 𝐰1 ← HighBits(𝐰)
1004            //  ▷ signer’s commitment
1005            let w1 = w.high_bits::<GAMMA2>();
1006
1007            {
1008                // scope for h
1009                // 15: 𝑐_tilde ← H(𝜇||w1Encode(𝐰1), 𝜆/4)
1010                //  ▷ commitment hash
1011                let mut hash = H::new();
1012                hash.absorb(mu).expect("absorb before squeeze is infallible");
1013                w1.w1_encode_and_hash::<POLY_W1_PACKED_LEN>(&mut hash);
1014                hash.squeeze_out(&mut sig_val_c_tilde);
1015            }
1016
1017            // 16: 𝑐 ∈ 𝑅𝑞 ← SampleInBall(c_tilde)
1018            //  ▷ verifier’s challenge
1019            let c_hat = {
1020                // scope for c
1021                let mut c = sample_in_ball::<LAMBDA_over_4, TAU>(&sig_val_c_tilde);
1022
1023                // 17: 𝑐_hat ← NTT(𝑐)
1024                c.ntt();
1025                c
1026            };
1027
1028            // 18: ⟨⟨𝑐𝐬1⟩⟩ ← NTT−1(𝑐_hat * 𝐬1_hat)
1029            //  Note: <<.>> in FIPS 204 means that this value will be used again later, so this should be kept.
1030            let mut cs1 = sk.s1_hat().scalar_vector_ntt(&c_hat);
1031            cs1.inv_ntt();
1032
1033            // 20: 𝐳 ← 𝐲 + ⟨⟨𝑐𝐬1⟩⟩
1034            y.add_vector_ntt(&cs1);
1035            sig_val_z = y;
1036
1037            // 23 (first half): if ||𝐳||∞ ≥ 𝛾1 − 𝛽 or ||𝐫0||∞ ≥ 𝛾2 − 𝛽 then (z, h) ← ⊥
1038            //  ▷ validity checks
1039            // This is done out-of-order on purpose for performance reasons:
1040            // rejection sampling check is done before any extra heavy computation
1041            if sig_val_z.check_norm::<GAMMA1_MINUS_BETA>() {
1042                kappa += l as u16;
1043                continue;
1044            };
1045
1046            // 19: ⟨⟨𝑐𝐬2⟩⟩ ← NTT−1(𝑐_hat * 𝐬2̂_hat)
1047            let mut cs2 = sk.s2_hat().scalar_vector_ntt(&c_hat);
1048            cs2.inv_ntt();
1049
1050            // 21: 𝐫0 ← LowBits(𝐰 − ⟨⟨𝑐𝐬2⟩⟩)
1051            let mut r0 = w.sub_vector(&cs2).low_bits::<GAMMA2>();
1052
1053            // 23 (second half): if ||𝐳||∞ ≥ 𝛾1 − 𝛽 or ||𝐫0||∞ ≥ 𝛾2 − 𝛽 then (z, h) ← ⊥
1054            //  ▷ validity checks
1055            //  Note: this could be further optimized by using the optimization described in
1056            //  https://pq-crystals.org/dilithium/data/dilithium-specification-round3-20210208.pdf section 5.1:
1057            //    "instead of computing (r1, r0) = Decomposeq (w − cs2, α)
1058            //      and checking whether ‖r0‖∞ < γ2 − β and r1 = w1, it is equivalent to just check that
1059            //      ‖w0 − cs2‖∞ < γ2 − β, where w0 is the low part of w. If this check passes, w0 − cs2
1060            //      is the low part of w − cs2."
1061            if r0.check_norm::<GAMMA2_MINUS_BETA>() {
1062                kappa += l as u16;
1063                continue;
1064            };
1065
1066            // 25: ⟨⟨𝑐𝐭0⟩⟩ ← NTT−1(𝑐_hat * 𝐭0̂_hat)
1067            let mut ct0 = sk.t0_hat().scalar_vector_ntt(&c_hat);
1068            ct0.inv_ntt();
1069
1070            // 28 (first half): if ||⟨⟨𝑐𝐭0⟩⟩||∞ ≥ 𝛾2 or the number of 1’s in 𝐡 is greater than 𝜔, then (z, h) ← ⊥
1071            // This is done out-of-order on purpose for performance reasons:
1072            // rejection sampling check is done before any extra heavy computation
1073            // mutants note: there is currently no unit test that triggers this branch
1074            if ct0.check_norm::<GAMMA2>() {
1075                kappa += l as u16;
1076                continue;
1077            };
1078
1079            // 26: 𝐡 ← MakeHint(−⟨⟨𝑐𝐭0⟩⟩, 𝐰 − ⟨⟨𝑐𝐬2⟩⟩ + ⟨⟨𝑐𝐭0⟩⟩)
1080            //  ▷ Signer’s hint
1081            r0.add_vector_ntt(&ct0);
1082            r0.conditional_add_q();
1083            let hint_hamming_weight: i32;
1084            sig_val_h = {
1085                // scope for hint
1086                let (hint, inner_hint_hamming_weight) = make_hint_vecs::<k, GAMMA2>(&r0, &w1);
1087                hint_hamming_weight = inner_hint_hamming_weight;
1088                hint
1089            };
1090
1091            // 28 (second half): if ||⟨⟨𝑐𝐭0⟩⟩||∞ ≥ 𝛾2 or the number of 1’s in 𝐡 is greater than 𝜔, then (z, h) ← ⊥
1092            // mutants note: there is no test KAT that triggers this branch
1093            if hint_hamming_weight > OMEGA {
1094                kappa += l as u16;
1095                continue;
1096            };
1097
1098            break;
1099        }
1100
1101        // zeroize rho_p_p before returning it to the OS
1102        rho_p_p.fill(0u8);
1103
1104        // sig_encode does not necessarily write to all bytes of the output, so just to be safe:
1105        output.fill(0u8);
1106
1107        // 33: 𝜎 ← sigEncode(𝑐, 𝐳̃ mod±𝑞, 𝐡)
1108        let bytes_written =
1109            sig_encode::<GAMMA1, k, l, LAMBDA_over_4, OMEGA, POLY_Z_PACKED_LEN, SIG_LEN>(
1110                &sig_val_c_tilde, &sig_val_z, &sig_val_h, output,
1111            );
1112
1113        Ok(bytes_written)
1114    }
1115
1116    /// Algorithm 8 ML-DSA.Verify_internal(𝑝𝑘, 𝑀′, 𝜎)
1117    /// Internal function to verify a signature 𝜎 for a formatted message 𝑀′ .
1118    /// Input: Public key 𝑝𝑘 ∈ 𝔹32+32𝑘(bitlen (𝑞−1)−𝑑) and message 𝑀′ ∈ {0, 1}∗ .
1119    /// Input: Signature 𝜎 ∈ 𝔹𝜆/4+ℓ⋅32⋅(1+bitlen (𝛾1−1))+𝜔+𝑘.
1120    fn verify_internal(
1121        pk: &PK,
1122        A_hat: &Matrix<k, l>,
1123        mu: &[u8; 64],
1124        sig: &[u8; SIG_LEN],
1125    ) -> Result<(), SignatureError> {
1126        // 1: (𝜌, 𝐭1) ← pkDecode(𝑝𝑘)
1127        // Already done -- the pk struct is already decoded
1128
1129        // 2: (𝑐_tilde, 𝐳, 𝐡) ← sigDecode(𝜎)
1130        //  ▷ signer’s commitment hash c_tilde, response 𝐳, and hint 𝐡
1131        // 3: if 𝐡 = ⊥ then return false
1132        let (c_tilde, z, h) =
1133            sig_decode::<GAMMA1, k, l, LAMBDA_over_4, OMEGA, POLY_Z_PACKED_LEN, SIG_LEN>(&sig)
1134                .map_err(|_| SignatureError::SignatureVerificationFailed)?;
1135
1136        // 13 (first half) return [[ ||𝐳||∞ < 𝛾1 − 𝛽]]
1137        if z.check_norm::<GAMMA1_MINUS_BETA>() {
1138            return Err(SignatureError::SignatureVerificationFailed);
1139        }
1140
1141        // 5: 𝐀 ← ExpandA(𝜌)
1142        //   ▷ 𝐀 is generated and stored in NTT representation as 𝐀
1143        // The code offers an optimization where the user can pre-expand A_hat within the
1144        // public key object for faster repeated encapsulations against this public key.
1145
1146        // 6: 𝑡𝑟 ← H(𝑝𝑘, 64)
1147        // 7: 𝜇 ← (H(BytesToBits(𝑡𝑟)||𝑀 ′, 64))
1148        //   ▷ message representative that may optionally be
1149        //     computed in a different cryptographic module
1150        // skip because this function is being handed mu
1151
1152        // 8: 𝑐 ∈ 𝑅𝑞 ← SampleInBall(c_tilde)
1153        let c_hat = {
1154            let mut c = sample_in_ball::<LAMBDA_over_4, TAU>(&c_tilde);
1155            c.ntt();
1156
1157            c
1158        };
1159
1160        // 9: 𝐰′_approx ← NTT−1(𝐀_hat ∘ NTT(𝐳) − NTT(𝑐) ∘ NTT(𝐭1 ⋅ 2^𝑑))
1161        //   broken out for clarity:
1162        //   NTT−1(
1163        //      𝐀_hat ∘ NTT(𝐳) −
1164        //                  NTT(𝑐) ∘ NTT(𝐭1 ⋅ 2^𝑑)
1165        //   )
1166        // ▷ 𝐰'_approx = 𝐀𝐳 − 𝑐𝐭1 ⋅ 2^𝑑
1167        // weird nested scoping is to reduce peak stack memory usage
1168        let w1p = {
1169            let Az = {
1170                let mut z_hat = z.clone();
1171                z_hat.ntt();
1172                A_hat.matrix_vector_ntt(&z_hat)
1173            };
1174            let ct1 = {
1175                // potential optimization -- pre-compute this on key load?
1176                let mut t1_shift_hat = pk.t1().shift_left::<d>();
1177                t1_shift_hat.ntt();
1178                t1_shift_hat.scalar_vector_ntt(&c_hat)
1179            };
1180            let mut wp_approx = Az.sub_vector(&ct1);
1181            wp_approx.inv_ntt();
1182            wp_approx.conditional_add_q();
1183
1184            // 10: 𝐰1′ ← UseHint(𝐡, 𝐰'_approx)
1185            // ▷ reconstruction of signer’s commitment
1186            use_hint_vecs::<k, GAMMA2>(&h, &wp_approx)
1187        };
1188        // 12: 𝑐_tilde_p ← H(𝜇||w1Encode(𝐰1'), 𝜆/4)
1189        // ▷ hash it; this should match 𝑐_tilde
1190        let c_tilde_p = {
1191            let mut c_tilde_p = [0u8; LAMBDA_over_4];
1192            let mut hash = H::new();
1193            hash.absorb(mu).expect("absorb before squeeze is infallible");
1194            w1p.w1_encode_and_hash::<POLY_W1_PACKED_LEN>(&mut hash);
1195            hash.squeeze_out(&mut c_tilde_p);
1196
1197            c_tilde_p
1198        };
1199
1200        // verification probably doesn't technically need to be constant-time, but why not?
1201        // 13 (second half): return [[ ||𝐳||∞ < 𝛾1 − 𝛽]] and [[𝑐 ̃ = 𝑐′ ]]
1202        if bouncycastle_utils::ct::ct_eq_bytes(&c_tilde, &c_tilde_p) {
1203            Ok(())
1204        } else {
1205            Err(SignatureError::SignatureVerificationFailed)
1206        }
1207    }
1208}
1209
1210impl<
1211    const PK_LEN: usize,
1212    const SK_LEN: usize,
1213    const SIG_LEN: usize,
1214    PK: MLDSAPublicKeyTrait<k, l, PK_LEN> + MLDSAPublicKeyInternalTrait<k, PK_LEN>,
1215    SK: MLDSAPrivateKeyTrait<k, l, ETA, SK_LEN, PK_LEN>
1216        + MLDSAPrivateKeyInternalTrait<k, l, ETA, SK_LEN, PK_LEN>,
1217    const TAU: i32,
1218    const LAMBDA: i32,
1219    const GAMMA1: i32,
1220    const GAMMA2: i32,
1221    const k: usize,
1222    const l: usize,
1223    const ETA: usize,
1224    const BETA: i32,
1225    const OMEGA: i32,
1226    const C_TILDE: usize,
1227    const POLY_Z_PACKED_LEN: usize,
1228    const POLY_W1_PACKED_LEN: usize,
1229    const LAMBDA_over_4: usize,
1230    const GAMMA1_MINUS_BETA: i32,
1231    const GAMMA2_MINUS_BETA: i32,
1232    const GAMMA1_MASK_LEN: usize,
1233> MLDSATrait<PK_LEN, SK_LEN, SIG_LEN, PK, SK, LAMBDA, k, l, ETA>
1234    for MLDSA<
1235        PK_LEN,
1236        SK_LEN,
1237        SIG_LEN,
1238        PK,
1239        SK,
1240        TAU,
1241        LAMBDA,
1242        GAMMA1,
1243        GAMMA2,
1244        k,
1245        l,
1246        ETA,
1247        BETA,
1248        OMEGA,
1249        C_TILDE,
1250        POLY_Z_PACKED_LEN,
1251        POLY_W1_PACKED_LEN,
1252        LAMBDA_over_4,
1253        GAMMA1_MINUS_BETA,
1254        GAMMA2_MINUS_BETA,
1255        GAMMA1_MASK_LEN,
1256    >
1257{
1258    fn keygen_from_seed(seed: &KeyMaterial<32>) -> Result<(PK, SK), SignatureError> {
1259        Self::keygen_internal(seed)
1260    }
1261    fn keygen_from_seed_and_encoded(
1262        seed: &KeyMaterial<32>,
1263        encoded_sk: &[u8; SK_LEN],
1264    ) -> Result<(PK, SK), SignatureError> {
1265        let (pk, sk) = Self::keygen_internal(seed)?;
1266
1267        let sk_from_bytes = SK::sk_decode(encoded_sk)?;
1268
1269        // MLDSAPrivateKey impls PartialEq with a constant-time equality check.
1270        if sk != sk_from_bytes {
1271            return Err(SignatureError::KeyGenError("Encoded key does not match generated key"));
1272        }
1273
1274        Ok((pk, sk))
1275    }
1276    fn keypair_consistency_check(pk: &PK, sk: &SK) -> Result<(), SignatureError> {
1277        // This is maybe a computationally heavy way to compare them, but it works
1278        let derived_pk = sk.derive_pk();
1279        if derived_pk.compute_tr() == pk.compute_tr() {
1280            Ok(())
1281        } else {
1282            Err(SignatureError::ConsistencyCheckFailed())
1283        }
1284    }
1285    fn compute_mu_from_tr(
1286        tr: &[u8; 64],
1287        msg: &[u8],
1288        ctx: Option<&[u8]>,
1289    ) -> Result<[u8; 64], SignatureError> {
1290        MuBuilder::compute_mu(tr, msg, ctx)
1291    }
1292    fn compute_mu_from_pk(
1293        pk: &impl MLDSAPublicKeyTrait<k, l, PK_LEN>,
1294        msg: &[u8],
1295        ctx: Option<&[u8]>,
1296    ) -> Result<[u8; 64], SignatureError> {
1297        MuBuilder::compute_mu(&pk.compute_tr(), msg, ctx)
1298    }
1299    fn compute_mu_from_sk(
1300        sk: &impl MLDSAPrivateKeyTrait<k, l, ETA, SK_LEN, PK_LEN>,
1301        msg: &[u8],
1302        ctx: Option<&[u8]>,
1303    ) -> Result<[u8; 64], SignatureError> {
1304        MuBuilder::compute_mu(&sk.tr(), msg, ctx)
1305    }
1306    fn sign_with_expanded_key(
1307        sk: &MLDSAPrivateKeyExpanded<k, l, ETA, PK, SK, SK_LEN, PK_LEN>,
1308        msg: &[u8],
1309        ctx: Option<&[u8]>,
1310    ) -> Result<[u8; SIG_LEN], SignatureError> {
1311        let mu = MuBuilder::compute_mu(&sk.tr(), msg, ctx)?;
1312        Self::sign_mu(&sk.sk, Some(&sk.A_hat), &mu)
1313    }
1314
1315    fn sign_with_expanded_key_out(
1316        sk: &MLDSAPrivateKeyExpanded<k, l, ETA, PK, SK, SK_LEN, PK_LEN>,
1317        msg: &[u8],
1318        ctx: Option<&[u8]>,
1319        out: &mut [u8; SIG_LEN],
1320    ) -> Result<usize, SignatureError> {
1321        out.fill(0);
1322
1323        let mu = MuBuilder::compute_mu(&sk.tr(), msg, ctx)?;
1324        Self::sign_mu_out(&sk.sk, Some(&sk.A_hat), &mu, out)
1325    }
1326
1327    fn sign_mu(
1328        sk: &SK,
1329        A_hat: Option<&Matrix<k, l>>,
1330        mu: &[u8; 64],
1331    ) -> Result<[u8; SIG_LEN], SignatureError> {
1332        let mut out: [u8; SIG_LEN] = [0u8; SIG_LEN];
1333        Self::sign_mu_out(sk, A_hat, mu, &mut out)?;
1334
1335        Ok(out)
1336    }
1337    fn sign_mu_out(
1338        sk: &SK,
1339        A_hat: Option<&Matrix<k, l>>,
1340        mu: &[u8; 64],
1341        output: &mut [u8; SIG_LEN],
1342    ) -> Result<usize, SignatureError> {
1343        output.fill(0);
1344
1345        let mut rnd: [u8; MLDSA_RND_LEN] = [0u8; MLDSA_RND_LEN];
1346        HashDRBG_SHA512::new_from_os().next_bytes_out(&mut rnd)?;
1347
1348        Self::sign_mu_deterministic_out(sk, A_hat, mu, rnd, output)
1349    }
1350    fn sign_mu_with_expanded_key(
1351        sk: &MLDSAPrivateKeyExpanded<k, l, ETA, PK, SK, SK_LEN, PK_LEN>,
1352        A_hat: Option<&Matrix<k, l>>,
1353        mu: &[u8; 64],
1354    ) -> Result<[u8; SIG_LEN], SignatureError> {
1355        let mut out: [u8; SIG_LEN] = [0u8; SIG_LEN];
1356        Self::sign_mu_with_expanded_key_out(sk, A_hat, mu, &mut out)?;
1357
1358        Ok(out)
1359    }
1360    fn sign_mu_with_expanded_key_out(
1361        sk: &MLDSAPrivateKeyExpanded<k, l, ETA, PK, SK, SK_LEN, PK_LEN>,
1362        A_hat: Option<&Matrix<k, l>>,
1363        mu: &[u8; 64],
1364        out: &mut [u8; SIG_LEN],
1365    ) -> Result<usize, SignatureError> {
1366        out.fill(0);
1367
1368        Self::sign_mu_out(&sk.sk, A_hat, mu, out)
1369    }
1370
1371    fn sign_mu_deterministic(
1372        sk: &SK,
1373        A_hat: Option<&Matrix<k, l>>,
1374        mu: &[u8; 64],
1375        rnd: [u8; 32],
1376    ) -> Result<[u8; SIG_LEN], SignatureError> {
1377        let mut out: [u8; SIG_LEN] = [0u8; SIG_LEN];
1378        Self::sign_mu_deterministic_out(sk, A_hat, mu, rnd, &mut out)?;
1379
1380        Ok(out)
1381    }
1382    fn sign_mu_deterministic_out(
1383        sk: &SK,
1384        A_hat: Option<&Matrix<k, l>>,
1385        mu: &[u8; 64],
1386        rnd: [u8; 32],
1387        output: &mut [u8; SIG_LEN],
1388    ) -> Result<usize, SignatureError> {
1389        output.fill(0);
1390
1391        match A_hat {
1392            Some(A_hat) => Self::sign_internal(sk, A_hat, mu, rnd, output),
1393            None => Self::sign_internal(sk, &sk.A_hat(), mu, rnd, output),
1394        }
1395    }
1396    fn sign_mu_deterministic_from_seed(
1397        seed: &KeyMaterial<32>,
1398        mu: &[u8; 64],
1399        rnd: [u8; 32],
1400    ) -> Result<[u8; SIG_LEN], SignatureError> {
1401        let mut out: [u8; SIG_LEN] = [0u8; SIG_LEN];
1402        Self::sign_mu_deterministic_from_seed_out(seed, mu, rnd, &mut out)?;
1403        Ok(out)
1404    }
1405    /// External-μ deterministic signing directly from a 32-byte seed (a mash-up of
1406    /// KeyGen Alg 6 and Sign Alg 7). Because μ is supplied by the caller, this never
1407    /// derives the public key: it skips pkEncode and tr = H(pk), never materializes
1408    /// the PK/SK structs, and keeps peak live memory low via scoped temporaries (see below).
1409    /// This is a middle ground between keygen_from_seed()+sign_mu() and
1410    /// the fully streamed low-memory implementation.
1411    // TODO: benchmark peak memory + runtime against
1412    // keygen_from_seed() + sign_mu_deterministic() to confirm the separate path earns being kept.
1413    // Note: this path intentionally avoids the public key entirely
1414    // (no pkEncode / tr = H(pk)) since μ is supplied externally.
1415    fn sign_mu_deterministic_from_seed_out(
1416        seed: &KeyMaterial<32>,
1417        mu: &[u8; 64],
1418        rnd: [u8; 32],
1419        output: &mut [u8; SIG_LEN],
1420    ) -> Result<usize, SignatureError> {
1421        output.fill(0);
1422
1423        // This has been kept as clean as possible for correspondence with the FIPS,
1424        // but things have been moved around so that unnamed scopes can be used to limit how many
1425        // stack variables are alive at the same time.
1426
1427        // 1: (𝜌, 𝐾, 𝑡𝑟, 𝐬1, 𝐬2, 𝐭0) ← skDecode(𝑠𝑘)
1428        // to avoid having all of it in memory at the same time,
1429        // we're gonna derive what we need as we need it.
1430
1431        if !(seed.key_type() == KeyType::Seed || seed.key_type() == KeyType::CryptographicRandom)
1432            || seed.key_len() != 32
1433        {
1434            return Err(SignatureError::KeyGenError(
1435                "Seed must be 32 bytes and KeyType::Seed or KeyType::BytesFullEntropy.",
1436            ));
1437        }
1438
1439        if seed.security_strength() < SecurityStrength::from_bits(LAMBDA as usize) {
1440            return Err(SignatureError::KeyGenError(
1441                "Seed SecurityStrength must match algorithm security strength: 128-bit (ML-DSA-44), 192-bit (ML-DSA-65), or 256-bit (ML-DSA-87).",
1442            ));
1443        }
1444
1445        // Alg 7; 6: 𝜇 ← H(BytesToBits(𝑡𝑟)||𝑀 ′, 64)
1446        // skip: mu has already been provided
1447
1448        let (rho, mut rho_p_p, s1, s2) = {
1449            // scope for h
1450            // derive sk.K
1451            // Alg 6; 1: (rho, rho_prime, K) <- H(𝜉||IntegerToBytes(𝑘, 1)||IntegerToBytes(ℓ, 1), 128)
1452            //   ▷ expand seed
1453            let (rho, rho_prime, K) = {
1454                let mut h = H::default();
1455                h.absorb(seed.ref_to_bytes()).expect("absorb before squeeze is infallible");
1456                h.absorb(&(k as u8).to_le_bytes()).expect("absorb before squeeze is infallible");
1457                h.absorb(&(l as u8).to_le_bytes()).expect("absorb before squeeze is infallible");
1458                let mut rho = [0u8; 32];
1459                let bytes_written = h.squeeze_out(&mut rho);
1460                debug_assert_eq!(bytes_written, 32);
1461                let mut rho_prime = [0u8; 64];
1462                let bytes_written = h.squeeze_out(&mut rho_prime);
1463                debug_assert_eq!(bytes_written, 64);
1464                let mut K: [u8; 32] = [0u8; 32];
1465                let bytes_written = h.squeeze_out(&mut K);
1466                debug_assert_eq!(bytes_written, 32);
1467
1468                (rho, rho_prime, K)
1469            };
1470
1471            // Alg 7; 7: 𝜌″ ← H(𝐾||𝑟𝑛𝑑||𝜇, 64)
1472            let rho_p_p = {
1473                let mut h = H::new();
1474                h.absorb(&K).expect("absorb before squeeze is infallible");
1475                h.absorb(&rnd).expect("absorb before squeeze is infallible");
1476                h.absorb(mu).expect("absorb before squeeze is infallible");
1477                let mut rho_p_p = [0u8; 64];
1478                h.squeeze_out(&mut rho_p_p);
1479
1480                rho_p_p
1481            };
1482
1483            // 4: (𝐬1, 𝐬2) ← ExpandS(𝜌′)
1484            let (s1, s2) = expandS::<k, l, ETA>(&rho_prime);
1485
1486            (rho, rho_p_p, s1, s2)
1487        };
1488
1489        // Alg 7; 5: 𝐀_hat ← ExpandA(𝜌)
1490        // Note on memory optimization:
1491        // A_hat consumes a large bit of memory and technically could move inside the loop --
1492        // -- or even more aggressively, could be derived and multiplied by y_hat row-by-row --
1493        // But in my unit tests, it can be observed that the loop typically execute 1 - 3 times, sometimes as many
1494        // as 20 or even 80 times. So moving expandA() inside the loop would be a pretty drastic speed-for-memory tradeoff
1495        // whose generality falls out of the scope of this implementation.
1496        // It is left as an optimization that can be made by users that require further reduction of memory usage
1497        let A_hat = expandA::<k, l>(&rho);
1498
1499        // Alg 7; 8: 𝜅 ← 0
1500        //  ▷ initialize counter 𝜅
1501        let mut kappa: u16 = 0;
1502
1503        // Alg 7; 9: (𝐳, 𝐡) ← ⊥
1504        // handled in the loop
1505
1506        // Alg 7; 10: while (𝐳, 𝐡) = ⊥ do
1507        //  ▷ rejection sampling loop
1508
1509        // these need to be outside the loop because they form the encoded signature value
1510        let mut sig_val_c_tilde = [0u8; LAMBDA_over_4];
1511        let mut sig_val_z: Vector<l>;
1512        let mut sig_val_h: Vector<k>;
1513        loop {
1514            // FIPS 204 s. 6.2 allows:
1515            //   "Implementations may limit the number of iterations in this loop to not exceed a finite maximum value."
1516            // mutants note: there is no test for this because we don't know of a KAT that will exceed this limit.
1517            if kappa > 1000 * k as u16 {
1518                return Err(SignatureError::GenericError(
1519                    "Rejection sampling loop exceeded max iterations, try again with a different signing nonce.",
1520                ));
1521            }
1522
1523            // Alg 7; 11: 𝐲 ∈ 𝑅^ℓ ← ExpandMask(𝜌″, 𝜅)
1524            let mut y = expand_mask::<l, GAMMA1, GAMMA1_MASK_LEN>(&rho_p_p, kappa);
1525
1526            let w = {
1527                // scope for y_hat
1528                // Alg 7; 12: 𝐰 ← NTT−1(𝐀_hat * NTT(𝐲))
1529                let mut y_hat = y.clone();
1530                y_hat.ntt();
1531                let mut w = A_hat.matrix_vector_ntt(&y_hat);
1532                w.inv_ntt();
1533                w.conditional_add_q();
1534                w
1535            };
1536
1537            // Alg 7; 13: 𝐰1 ← HighBits(𝐰)
1538            //  ▷ signer’s commitment
1539            let w1 = w.high_bits::<GAMMA2>();
1540
1541            {
1542                // scope for h
1543                // 15: 𝑐_tilde ← H(𝜇||w1Encode(𝐰1), 𝜆/4)
1544                //  ▷ commitment hash
1545                let mut hash = H::new();
1546                hash.absorb(mu).expect("absorb before squeeze is infallible");
1547                w1.w1_encode_and_hash::<POLY_W1_PACKED_LEN>(&mut hash);
1548                hash.squeeze_out(&mut sig_val_c_tilde);
1549            }
1550
1551            // Alg 7; 16: 𝑐 ∈ 𝑅𝑞 ← SampleInBall(c_tilde)
1552            //  ▷ verifier’s challenge
1553            let c_hat = {
1554                // scope for c
1555                let mut c = sample_in_ball::<LAMBDA_over_4, TAU>(&sig_val_c_tilde);
1556
1557                // 17: 𝑐_hat ← NTT(𝑐)
1558                c.ntt();
1559                c
1560            };
1561
1562            let t_hat: Vector<k>;
1563            sig_val_z = {
1564                // scope for s1_hat, cs1
1565                // Alg 7; 2: 𝐬1̂_hat ← NTT(𝐬1)
1566                let mut s1_hat = s1.clone();
1567                s1_hat.ntt();
1568
1569                y = {
1570                    // scope for cs1
1571                    // Alg 7; 18: ⟨⟨𝑐𝐬1⟩⟩ ← NTT−1(𝑐_hat * 𝐬1_hat)
1572                    // Note: <<.>> in FIPS 204 means that this value will be used again later,
1573                    // so it is better to keep it.
1574                    let mut cs1 = s1_hat.scalar_vector_ntt(&c_hat);
1575                    cs1.inv_ntt();
1576
1577                    // Alg 7; 20: 𝐳 ← 𝐲 + ⟨⟨𝑐𝐬1⟩⟩
1578                    y.add_vector_ntt(&cs1);
1579                    y
1580                };
1581
1582                // also, while we have s1_hat in memory, compute t_hat
1583                // Alg 6; 5: 𝐭 ← NTT−1(𝐀 ∘ NTT(𝐬1)) + 𝐬2
1584                //   ▷ compute 𝐭 = 𝐀𝐬1 + 𝐬2
1585                t_hat = A_hat.matrix_vector_ntt(&s1_hat);
1586
1587                y
1588            };
1589
1590            // Alg 7; 23 (first half): if ||𝐳||∞ ≥ 𝛾1 − 𝛽 or ||𝐫0||∞ ≥ 𝛾2 − 𝛽 then (z, h) ← ⊥
1591            //  ▷ validity checks
1592            // This is done out-of-order on purpose for performance reasons:
1593            // rejection sampling check is done before any extra heavy computation
1594            if sig_val_z.check_norm::<GAMMA1_MINUS_BETA>() {
1595                kappa += l as u16;
1596                continue;
1597            };
1598
1599            let t0: Vector<k>;
1600            let mut r0: Vector<k> = {
1601                // scope for s2_hat and cs2
1602                // 3: 𝐬2̂_hat ← NTT(𝐬2)
1603                let mut s2_hat = s2.clone();
1604                s2_hat.ntt();
1605
1606                // 19: ⟨⟨𝑐𝐬2⟩⟩ ← NTT−1(𝑐_hat * 𝐬2̂_hat)
1607                let mut cs2 = s2_hat.scalar_vector_ntt(&c_hat);
1608                cs2.inv_ntt();
1609
1610                // 21: 𝐫0 ← LowBits(𝐰 − ⟨⟨𝑐𝐬2⟩⟩)
1611                let r0 = w.sub_vector(&cs2).low_bits::<GAMMA2>();
1612
1613                // while s2_hat is in scope, derive t0
1614                let mut t = t_hat;
1615                t.inv_ntt();
1616                t.add_vector_ntt(&s2);
1617                t.conditional_add_q();
1618
1619                // 6: (𝐭1, 𝐭0) ← Power2Round(𝐭)
1620                //   ▷ compress 𝐭
1621                //   ▷ PowerTwoRound is applied componentwise (see explanatory text in Section 7.4)
1622                let (_t1tmp, t0tmp) = power_2_round_vec::<k>(&t);
1623                t0 = t0tmp;
1624
1625                r0
1626            };
1627
1628            // Alg 7; 23 (second half): if ||𝐳||∞ ≥ 𝛾1 − 𝛽 or ||𝐫0||∞ ≥ 𝛾2 − 𝛽 then (z, h) ← ⊥
1629            //  ▷ validity checks
1630            if r0.check_norm::<GAMMA2_MINUS_BETA>() {
1631                // mutants note: mutants thinks this can be replaced with -=, but in practice that makes
1632                //               the rejection sampling loop go forever, so is a false positive.
1633                kappa += l as u16;
1634                continue;
1635            };
1636
1637            let ct0: Vector<k> = {
1638                // scope for t0_hat
1639                // 4: 𝐭0̂_hat ← NTT(𝐭0)̂
1640                let mut t0_hat = t0.clone();
1641                t0_hat.ntt();
1642
1643                // 25: ⟨⟨𝑐𝐭0⟩⟩ ← NTT−1(𝑐_hat * 𝐭0̂_hat )
1644                let mut ct0 = t0_hat.scalar_vector_ntt(&c_hat);
1645                ct0.inv_ntt();
1646                ct0
1647            };
1648
1649            // Alg 7; 28 (first half): if ||⟨⟨𝑐𝐭0⟩⟩||∞ ≥ 𝛾2 or the number of 1’s in 𝐡 is greater than 𝜔, then (z, h) ← ⊥
1650            // out-of-order on purpose for performance reasons:
1651            //   might as well do the rejection sampling check before any extra heavy computation
1652            // mutants note: there is currently no unit test that triggers this branch
1653            if ct0.check_norm::<GAMMA2>() {
1654                kappa += l as u16;
1655                continue;
1656            };
1657
1658            // Alg 7; 26: 𝐡 ← MakeHint(−⟨⟨𝑐𝐭0⟩⟩, 𝐰 − ⟨⟨𝑐𝐬2⟩⟩ + ⟨⟨𝑐𝐭0⟩⟩)
1659            //  ▷ Signer’s hint
1660            r0.add_vector_ntt(&ct0);
1661            r0.conditional_add_q();
1662            let hint_hamming_weight: i32;
1663            sig_val_h = {
1664                // scope for hint
1665                let (hint, inner_hint_hamming_weight) = make_hint_vecs::<k, GAMMA2>(&r0, &w1);
1666                hint_hamming_weight = inner_hint_hamming_weight;
1667                hint
1668            };
1669
1670            // Alg 7; 28 (second half): if ||⟨⟨𝑐𝐭0⟩⟩||∞ ≥ 𝛾2 or the number of 1’s in 𝐡 is greater than 𝜔, then (z, h) ← ⊥
1671            // mutants note: there is currently no unit test that triggers this branch
1672            if hint_hamming_weight > OMEGA {
1673                kappa += l as u16;
1674                continue;
1675            };
1676
1677            break;
1678        }
1679
1680        // zeroize rho_p_p before returning it to the OS
1681        rho_p_p.fill(0u8);
1682
1683        // sig_encode does not necessarily write to all bytes of the output,
1684        // The following is done for safety
1685        output.fill(0u8);
1686
1687        // Alg 7; 33: 𝜎 ← sigEncode(𝑐, 𝐳̃ mod±𝑞, 𝐡)
1688        let bytes_written =
1689            sig_encode::<GAMMA1, k, l, LAMBDA_over_4, OMEGA, POLY_Z_PACKED_LEN, SIG_LEN>(
1690                &sig_val_c_tilde, &sig_val_z, &sig_val_h, output,
1691            );
1692
1693        Ok(bytes_written)
1694    }
1695    fn set_signer_rnd(&mut self, rnd: [u8; 32]) {
1696        self.signer_rnd = Some(rnd);
1697    }
1698    fn sign_init_from_seed(
1699        seed: &KeyMaterial<32>,
1700        ctx: Option<&[u8]>,
1701    ) -> Result<Self, SignatureError> {
1702        let (_pk, sk) = Self::keygen_from_seed(seed)?;
1703        Ok(Self {
1704            _phantom: PhantomData,
1705            mu_builder: MuBuilder::do_init(&sk.tr(), ctx)?,
1706            signer_rnd: None,
1707            sk: None,
1708            seed: Some(seed.clone()),
1709            pk: None,
1710        })
1711    }
1712
1713    fn verify_with_expanded_key(
1714        pk: &MLDSAPublicKeyExpanded<k, l, PK, PK_LEN>,
1715        msg: &[u8],
1716        ctx: Option<&[u8]>,
1717        sig: &[u8],
1718    ) -> Result<(), SignatureError> {
1719        let mu = MuBuilder::compute_mu(&pk.compute_tr(), msg, ctx)?;
1720        let sig: &[u8; SIG_LEN] = sig.try_into().map_err(|_| {
1721            SignatureError::LengthError("Signature value is not the correct length.")
1722        })?;
1723        Self::verify_mu(&pk.pk, Some(&pk.A_hat()), &mu, sig)
1724    }
1725
1726    fn verify_mu(
1727        pk: &PK,
1728        A_hat: Option<&Matrix<k, l>>,
1729        mu: &[u8; 64],
1730        sig: &[u8; SIG_LEN],
1731    ) -> Result<(), SignatureError> {
1732        match A_hat {
1733            Some(A_hat) => Self::verify_internal(pk, A_hat, mu, sig),
1734            None => Self::verify_internal(pk, &pk.A_hat(), mu, sig),
1735        }
1736    }
1737}
1738
1739/// Trait for all three of the ML-DSA algorithm variants.
1740pub trait MLDSATrait<
1741    const PK_LEN: usize,
1742    const SK_LEN: usize,
1743    const SIG_LEN: usize,
1744    PK: MLDSAPublicKeyTrait<k, l, PK_LEN> + MLDSAPublicKeyInternalTrait<k, PK_LEN>,
1745    SK: MLDSAPrivateKeyTrait<k, l, ETA, SK_LEN, PK_LEN>
1746        + MLDSAPrivateKeyInternalTrait<k, l, ETA, SK_LEN, PK_LEN>,
1747    const LAMBDA: i32,
1748    const k: usize,
1749    const l: usize,
1750    const ETA: usize,
1751>: Sized
1752{
1753    /// Runs a key generation using the library's default RNG, seeded from the OS.
1754    /// In environments where the default OS based RNG is not available, use instead [`MLDSA::keygen_from_rng`]
1755    /// and explicitly provide a [`RNG`] implementation, or use [`MLDSATrait::keygen_from_seed`] and provide the
1756    /// private key seed directly.
1757    fn keygen() -> Result<(PK, SK), SignatureError> {
1758        let mut os_rng = HashDRBG_SHA512::new_from_os();
1759        Self::keygen_from_rng(&mut os_rng)
1760    }
1761    /// Run a keygen using the provided RNG implementation.
1762    // Should still be ok in FIPS mode, provided that you're using the FIPS-approved RNG.
1763    fn keygen_from_rng(rng: &mut dyn RNG) -> Result<(PK, SK), SignatureError> {
1764        // Source the seed from the provided RNG
1765        if rng.security_strength() < SecurityStrength::from_bits(LAMBDA as usize) {
1766            return Err(RNGError::SecurityStrengthInsufficientForAlgorithm)?;
1767        }
1768        let mut seed = KeyMaterial256::new();
1769        rng.fill_keymaterial_out(&mut seed)?;
1770        Self::keygen_from_seed(&seed)
1771    }
1772    /// Imports a secret key from a seed.
1773    fn keygen_from_seed(seed: &KeyMaterial<32>) -> Result<(PK, SK), SignatureError>;
1774    /// Imports a secret key from both a seed and an encoded_sk.
1775    ///
1776    /// This is a convenience function to expand the key from seed and compare it against
1777    /// the provided `encoded_sk` using a constant-time equality check.
1778    /// If everything checks out, the secret key is returned fully populated with pk and seed.
1779    /// If the provided key and derived key don't match, an error is returned.
1780    fn keygen_from_seed_and_encoded(
1781        seed: &KeyMaterial<32>,
1782        encoded_sk: &[u8; SK_LEN],
1783    ) -> Result<(PK, SK), SignatureError>;
1784    /// Given a public key and a secret key, check that the public key matches the secret key.
1785    /// This is a sanity check that the public key was generated correctly from the secret key.
1786    ///
1787    /// At the current time, this is only possible if `sk` either contains a public key (in which case
1788    /// the two pk's are encoded and compared for byte equality), or if `sk` contains a seed
1789    /// (in which case a keygen_from_seed is run and then the pk's compared).
1790    ///
1791    /// Returns either `()` or [`SignatureError::ConsistencyCheckFailed`].
1792    fn keypair_consistency_check(pk: &PK, sk: &SK) -> Result<(), SignatureError>;
1793    /// This provides the first half of the "External Mu" interface to ML-DSA which is described
1794    /// in, and allowed under, NIST's FAQ that accompanies FIPS 204.
1795    ///
1796    /// This function, together with [`MLDSATrait::sign_mu`] perform a complete ML-DSA signature which is indistinguishable
1797    /// from one produced by the one-shot sign APIs.
1798    ///
1799    /// The utility of this function is exactly as described
1800    /// on Line 6 of Algorithm 7 of FIPS 204:
1801    ///
1802    ///    message representative that may optionally be computed in a different cryptographic module
1803    ///
1804    /// The utility is when an extremely large message needs to be signed, where the message exists on one
1805    /// computing system and the private key to sign it is held on another and either the transfer time or bandwidth
1806    /// causes operational concerns (this is common for example with network HSMs or sending large messages
1807    /// to be signed by a smartcard communicating over near-field radio). Another use case is if the
1808    /// contents of the message are sensitive and the signer does not want to transmit the message itself
1809    /// for fear of leaking it via proxy logging and instead would prefer to only transmit a hash of it.
1810    ///
1811    /// Since "External Mu" mode is well-defined by FIPS 204 and allowed by NIST, the mu value produced here
1812    /// can be used with many hardware crypto modules.
1813    ///
1814    /// This "External Mu" mode of ML-DSA provides an alternative to the HashML-DSA algorithm in that it
1815    /// allows the message to be externally pre-hashed, however, unlike HashML-DSA, this is merely an optimization
1816    /// between the application holding the to-be-signed message and the cryptographic module holding the private key
1817    /// -- in particular, while HashML-DSA requires the verifier to know whether ML-DSA or HashML-DSA was used to sign
1818    /// the message, both "direct" ML-DSA and "External Mu" signatures can be verified with a standard
1819    /// ML-DSA verifier.
1820    ///
1821    /// This function requires the public key hash `tr`, which can be computed from the public key
1822    /// using [`MLDSAPublicKeyTrait::compute_tr`].
1823    ///
1824    /// For a streaming version of this, see [`MuBuilder`].
1825    fn compute_mu_from_tr(
1826        tr: &[u8; 64],
1827        msg: &[u8],
1828        ctx: Option<&[u8]>,
1829    ) -> Result<[u8; 64], SignatureError>;
1830    /// Same as [`MLDSATrait::compute_mu_from_tr`], but extracts tr from the public key.
1831    fn compute_mu_from_pk(
1832        pk: &impl MLDSAPublicKeyTrait<k, l, PK_LEN>,
1833        msg: &[u8],
1834        ctx: Option<&[u8]>,
1835    ) -> Result<[u8; 64], SignatureError>;
1836    /// Same as [`MLDSATrait::compute_mu_from_tr`], but extracts tr from the private key.
1837    // dev note: defined sk this way so that it accepts either MLDSAPrivateKey or MLDSAPRivateKeyExpanded
1838    fn compute_mu_from_sk(
1839        sk: &impl MLDSAPrivateKeyTrait<k, l, ETA, SK_LEN, PK_LEN>,
1840        msg: &[u8],
1841        ctx: Option<&[u8]>,
1842    ) -> Result<[u8; 64], SignatureError>;
1843    /// Same as [`Signer::sign`], but signs from an [`MLDSAPrivateKeyExpanded`].
1844    fn sign_with_expanded_key(
1845        sk: &MLDSAPrivateKeyExpanded<k, l, ETA, PK, SK, SK_LEN, PK_LEN>,
1846        msg: &[u8],
1847        ctx: Option<&[u8]>,
1848    ) -> Result<[u8; SIG_LEN], SignatureError>;
1849    /// Same as [`MLDSATrait::sign_with_expanded_key`], but takes an output array.
1850    fn sign_with_expanded_key_out(
1851        sk: &MLDSAPrivateKeyExpanded<k, l, ETA, PK, SK, SK_LEN, PK_LEN>,
1852        msg: &[u8],
1853        ctx: Option<&[u8]>,
1854        out: &mut [u8; SIG_LEN],
1855    ) -> Result<usize, SignatureError>;
1856    /// Performs an ML-DSA signature using the provided external message representative `mu`.
1857    /// This implements FIPS 204 Algorithm 7 with line 6 removed; a modification that is allowed by both
1858    /// FIPS 204 itself, as well as subsequent FAQ documents.
1859    /// This mode uses randomized signing (called "hedged mode" in FIPS 204) using an internal RNG.
1860    ///
1861    /// Optionally, takes a pre-expanded public matrix `A_hat`.
1862    fn sign_mu(
1863        sk: &SK,
1864        A_hat: Option<&Matrix<k, l>>,
1865        mu: &[u8; 64],
1866    ) -> Result<[u8; SIG_LEN], SignatureError>;
1867    /// Performs an ML-DSA signature using the provided external message representative `mu`.
1868    /// This implements FIPS 204 Algorithm 7 with line 6 removed; a modification that is allowed by both
1869    /// FIPS 204 itself, as well as subsequent FAQ documents.
1870    /// This mode uses randomized signing (called "hedged mode" in FIPS 204) using an internal RNG.
1871    ///
1872    /// Optionally takes the public matrix A_hat which can be extracted from either the public key or private
1873    /// key object -- although the more ergonomic way to use this functionality is via the
1874    /// [`MLDSAPublicKeyExpanded`] object.
1875    ///
1876    /// Returns the number of bytes written to the output buffer. Can be called with an oversized buffer.
1877    fn sign_mu_out(
1878        sk: &SK,
1879        A_hat: Option<&Matrix<k, l>>,
1880        mu: &[u8; 64],
1881        output: &mut [u8; SIG_LEN],
1882    ) -> Result<usize, SignatureError>;
1883    /// Same as [`MLDSATrait::sign_mu`], but signs from an [`MLDSAPrivateKeyExpanded`].
1884    fn sign_mu_with_expanded_key(
1885        sk: &MLDSAPrivateKeyExpanded<k, l, ETA, PK, SK, SK_LEN, PK_LEN>,
1886        A_hat: Option<&Matrix<k, l>>,
1887        mu: &[u8; 64],
1888    ) -> Result<[u8; SIG_LEN], SignatureError>;
1889    /// Same as [`MLDSATrait::sign_mu_out`], but signs from an [`MLDSAPrivateKeyExpanded`].
1890    fn sign_mu_with_expanded_key_out(
1891        sk: &MLDSAPrivateKeyExpanded<k, l, ETA, PK, SK, SK_LEN, PK_LEN>,
1892        A_hat: Option<&Matrix<k, l>>,
1893        mu: &[u8; 64],
1894        output: &mut [u8; SIG_LEN],
1895    ) -> Result<usize, SignatureError>;
1896    /// Algorithm 7 ML-DSA.Sign_internal(𝑠𝑘, 𝑀′, 𝑟𝑛𝑑)
1897    /// (modified to take an externally-computed mu instead of M')
1898    ///
1899    /// Performs an ML-DSA signature using the provided external message representative `mu`.
1900    /// This implements FIPS 204 Algorithm 7 with line 6 removed; a modification that is allowed by both
1901    /// FIPS 204 itself, as well as subsequent FAQ documents.
1902    ///
1903    /// Optionally takes the public matrix A_hat which can be extracted from either the public key or private
1904    /// key object -- although the more ergonomic way to use this functionality is via the
1905    /// [`MLDSAPublicKeyExpanded`] object.
1906    ///
1907    /// Security note about deterministic mode:
1908    /// This mode exposes deterministic signing (called "hedged mode" and allowed by FIPS 204).
1909    /// The ML-DSA algorithm is considered safe to use in deterministic mode, but be aware that
1910    /// the responsibility is on the user to ensure that the nonce `rnd` is unique for each signature.
1911    /// If not, some privacy properties may be lost; for example it becomes easy to tell if a signer
1912    /// has signed the same message twice or two different messagase, or to tell if the same message
1913    /// has been signed by the same signer twice or two different signers.
1914    ///
1915    /// Since `rnd` should be either a per-signature nonce, or a fixed value, therefore, to help
1916    /// prevent accidental nonce reuse, this function moves `rnd`.
1917    fn sign_mu_deterministic(
1918        sk: &SK,
1919        A_hat: Option<&Matrix<k, l>>,
1920        mu: &[u8; 64],
1921        rnd: [u8; 32],
1922    ) -> Result<[u8; SIG_LEN], SignatureError>;
1923    /// Algorithm 7 ML-DSA.Sign_internal(𝑠𝑘, 𝑀′, 𝑟𝑛𝑑)
1924    /// (modified to take an externally-computed mu instead of M')
1925    ///
1926    /// Performs an ML-DSA signature using the provided external message representative `mu`.
1927    /// This implements FIPS 204 Algorithm 7 with line 6 removed; a modification that is allowed by both
1928    /// FIPS 204 itself, as well as subsequent FAQ documents.
1929    /// This mode exposes deterministic signing (called "hedged mode" in FIPS 204) using an internal RNG.
1930    ///
1931    /// This mode exposes the signing nonce `rnd` either for users who wish to source the signing
1932    /// nonce from a source other than the library's default internal RNG, or who wish to use the
1933    /// "deterministic mode" defined in FIPS 204 by providing `rnd = [0u8; 32]`.
1934    /// In order to help prevent against accidental nonce reuse, this function moves `rnd` instead
1935    /// of taking it by reference.
1936    ///
1937    /// Security note about deterministic mode:
1938    /// This mode exposes deterministic signing (called "hedged mode" and allowed by FIPS 204).
1939    /// The ML-DSA algorithm is considered safe to use in deterministic mode, but be aware that
1940    /// the responsibility is on the user to ensure that the nonce `rnd` is unique for each signature.
1941    /// If not, some privacy properties may be lost; for example, it becomes easy to tell if a signer
1942    /// has signed the same message twice or two different messages, or to tell if the same message
1943    /// has been signed by the same signer twice or two different signers.
1944    ///
1945    /// Returns the number of bytes written to the output buffer. Can be called with an oversized buffer.
1946    fn sign_mu_deterministic_out(
1947        sk: &SK,
1948        A_hat: Option<&Matrix<k, l>>,
1949        mu: &[u8; 64],
1950        rnd: [u8; 32],
1951        output: &mut [u8; SIG_LEN],
1952    ) -> Result<usize, SignatureError>;
1953    /// This contains a heavily-optimized combined keygen() and sign() which greatly reduces peak
1954    /// memory usage by never having the full secret key in memory at the same time,
1955    /// and by deriving intermediate values piece-wise as needed.
1956    fn sign_mu_deterministic_from_seed(
1957        seed: &KeyMaterial<32>,
1958        mu: &[u8; 64],
1959        rnd: [u8; 32],
1960    ) -> Result<[u8; SIG_LEN], SignatureError>;
1961    /// This contains a heavily-optimized combined keygen() and sign() which greatly reduces peak
1962    /// memory usage by never having the full secret key in memory at the same time,
1963    /// and by deriving intermediate values piece-wise as needed.
1964    fn sign_mu_deterministic_from_seed_out(
1965        seed: &KeyMaterial<32>,
1966        mu: &[u8; 64],
1967        rnd: [u8; 32],
1968        output: &mut [u8; SIG_LEN],
1969    ) -> Result<usize, SignatureError>;
1970    /// To be used for deterministic signing in conjunction with the [`MLDSA44::sign_init`], [`MLDSA44::sign_update`], and [`MLDSA44::sign_final`] flow.
1971    /// Can be set anywhere after [`MLDSA44::sign_init`] and before [`MLDSA44::sign_final`].
1972    fn set_signer_rnd(&mut self, rnd: [u8; 32]);
1973    /// Alternative initialization of the streaming signer where the user has their private key
1974    /// as a seed and they want to delay its expansion as late as possible for memory-usage reasons.
1975    fn sign_init_from_seed(
1976        seed: &KeyMaterial<32>,
1977        ctx: Option<&[u8]>,
1978    ) -> Result<Self, SignatureError>;
1979    /// Same as [`SignatureVerifier::verify`], but signs from an expanded key object.
1980    fn verify_with_expanded_key(
1981        pk: &MLDSAPublicKeyExpanded<k, l, PK, PK_LEN>,
1982        msg: &[u8],
1983        ctx: Option<&[u8]>,
1984        sig: &[u8],
1985    ) -> Result<(), SignatureError>;
1986    /// Performs an ML-DSA signature verification using the provided external message representative `mu`.
1987    /// This implements FIPS 204 Algorithm 8 with line 7 removed; a modification that is allowed by both
1988    /// FIPS 204 itself, as well as subsequent FAQ documents.
1989    /// Optionally, takes a pre-expanded public matrix `A_hat`.
1990    fn verify_mu(
1991        pk: &PK,
1992        A_hat: Option<&Matrix<k, l>>,
1993        mu: &[u8; 64],
1994        sig: &[u8; SIG_LEN],
1995    ) -> Result<(), SignatureError>;
1996}
1997
1998impl<
1999    const PK_LEN: usize,
2000    const SK_LEN: usize,
2001    const SIG_LEN: usize,
2002    PK: MLDSAPublicKeyTrait<k, l, PK_LEN> + MLDSAPublicKeyInternalTrait<k, PK_LEN>,
2003    SK: MLDSAPrivateKeyTrait<k, l, ETA, SK_LEN, PK_LEN>
2004        + MLDSAPrivateKeyInternalTrait<k, l, ETA, SK_LEN, PK_LEN>,
2005    const TAU: i32,
2006    const LAMBDA: i32,
2007    const GAMMA1: i32,
2008    const GAMMA2: i32,
2009    const k: usize,
2010    const l: usize,
2011    const ETA: usize,
2012    const BETA: i32,
2013    const OMEGA: i32,
2014    const C_TILDE: usize,
2015    const POLY_Z_PACKED_LEN: usize,
2016    const POLY_W1_PACKED_LEN: usize,
2017    const LAMBDA_over_4: usize,
2018    const GAMMA1_MINUS_BETA: i32,
2019    const GAMMA2_MINUS_BETA: i32,
2020    const GAMMA1_MASK_LEN: usize,
2021> Signer<SK, SK_LEN, SIG_LEN>
2022    for MLDSA<
2023        PK_LEN,
2024        SK_LEN,
2025        SIG_LEN,
2026        PK,
2027        SK,
2028        TAU,
2029        LAMBDA,
2030        GAMMA1,
2031        GAMMA2,
2032        k,
2033        l,
2034        ETA,
2035        BETA,
2036        OMEGA,
2037        C_TILDE,
2038        POLY_Z_PACKED_LEN,
2039        POLY_W1_PACKED_LEN,
2040        LAMBDA_over_4,
2041        GAMMA1_MINUS_BETA,
2042        GAMMA2_MINUS_BETA,
2043        GAMMA1_MASK_LEN,
2044    >
2045{
2046    fn sign(sk: &SK, msg: &[u8], ctx: Option<&[u8]>) -> Result<[u8; SIG_LEN], SignatureError> {
2047        let mut out = [0u8; SIG_LEN];
2048        Self::sign_out(sk, msg, ctx, &mut out)?;
2049
2050        Ok(out)
2051    }
2052
2053    fn sign_out(
2054        sk: &SK,
2055        msg: &[u8],
2056        ctx: Option<&[u8]>,
2057        output: &mut [u8; SIG_LEN],
2058    ) -> Result<usize, SignatureError> {
2059        output.fill(0);
2060
2061        let mu = MuBuilder::compute_mu(&sk.tr(), msg, ctx)?;
2062        let bytes_written = Self::sign_mu_out(sk, None, &mu, output)?;
2063
2064        Ok(bytes_written)
2065    }
2066
2067    fn sign_init(sk: &SK, ctx: Option<&[u8]>) -> Result<Self, SignatureError> {
2068        Ok(Self {
2069            _phantom: PhantomData,
2070            mu_builder: MuBuilder::do_init(&sk.tr(), ctx)?,
2071            signer_rnd: None,
2072            sk: Some(sk.clone()),
2073            seed: None,
2074            pk: None,
2075        })
2076    }
2077
2078    fn sign_update(&mut self, msg_chunk: &[u8]) {
2079        self.mu_builder.do_update(msg_chunk);
2080    }
2081
2082    fn sign_final(self) -> Result<[u8; SIG_LEN], SignatureError> {
2083        let mut out = [0u8; SIG_LEN];
2084        self.sign_final_out(&mut out)?;
2085        Ok(out)
2086    }
2087
2088    fn sign_final_out(self, output: &mut [u8; SIG_LEN]) -> Result<usize, SignatureError> {
2089        let mu = self.mu_builder.do_final();
2090
2091        if self.sk.is_none() && self.seed.is_none() {
2092            return Err(SignatureError::GenericError(
2093                "sign_final_out called on a streaming context with no private key or seed; \
2094     			this is a verify-initialized context. Call verify_final instead",
2095            ));
2096        }
2097
2098        output.fill(0);
2099
2100        if self.sk.is_some() {
2101            if self.signer_rnd.is_none() {
2102                Self::sign_mu_out(&self.sk.unwrap(), None, &mu, output)
2103            } else {
2104                Self::sign_mu_deterministic_out(
2105                    &self.sk.unwrap(),
2106                    None,
2107                    &mu,
2108                    self.signer_rnd.unwrap(),
2109                    output,
2110                )
2111            }
2112        } else if self.seed.is_some() {
2113            let rnd = if self.signer_rnd.is_some() {
2114                self.signer_rnd.unwrap()
2115            } else {
2116                let mut rnd: [u8; MLDSA_RND_LEN] = [0u8; MLDSA_RND_LEN];
2117                HashDRBG_SHA512::new_from_os().next_bytes_out(&mut rnd)?;
2118                rnd
2119            };
2120            Self::sign_mu_deterministic_from_seed_out(&self.seed.unwrap(), &mu, rnd, output)
2121        } else {
2122            unreachable!()
2123        }
2124    }
2125}
2126
2127impl<
2128    const PK_LEN: usize,
2129    const SK_LEN: usize,
2130    const SIG_LEN: usize,
2131    PK: MLDSAPublicKeyTrait<k, l, PK_LEN> + MLDSAPublicKeyInternalTrait<k, PK_LEN>,
2132    SK: MLDSAPrivateKeyTrait<k, l, ETA, SK_LEN, PK_LEN>
2133        + MLDSAPrivateKeyInternalTrait<k, l, ETA, SK_LEN, PK_LEN>,
2134    const TAU: i32,
2135    const LAMBDA: i32,
2136    const GAMMA1: i32,
2137    const GAMMA2: i32,
2138    const k: usize,
2139    const l: usize,
2140    const ETA: usize,
2141    const BETA: i32,
2142    const OMEGA: i32,
2143    const C_TILDE: usize,
2144    const POLY_Z_PACKED_LEN: usize,
2145    const POLY_W1_PACKED_LEN: usize,
2146    const LAMBDA_over_4: usize,
2147    const GAMMA1_MINUS_BETA: i32,
2148    const GAMMA2_MINUS_BETA: i32,
2149    const GAMMA1_MASK_LEN: usize,
2150> SignatureVerifier<PK, PK_LEN, SIG_LEN>
2151    for MLDSA<
2152        PK_LEN,
2153        SK_LEN,
2154        SIG_LEN,
2155        PK,
2156        SK,
2157        TAU,
2158        LAMBDA,
2159        GAMMA1,
2160        GAMMA2,
2161        k,
2162        l,
2163        ETA,
2164        BETA,
2165        OMEGA,
2166        C_TILDE,
2167        POLY_Z_PACKED_LEN,
2168        POLY_W1_PACKED_LEN,
2169        LAMBDA_over_4,
2170        GAMMA1_MINUS_BETA,
2171        GAMMA2_MINUS_BETA,
2172        GAMMA1_MASK_LEN,
2173    >
2174{
2175    fn verify(pk: &PK, msg: &[u8], ctx: Option<&[u8]>, sig: &[u8]) -> Result<(), SignatureError> {
2176        let mu = MuBuilder::compute_mu(&pk.compute_tr(), msg, ctx)?;
2177        let sig: &[u8; SIG_LEN] = sig.try_into().map_err(|_| {
2178            SignatureError::LengthError("Signature value is not the correct length.")
2179        })?;
2180        Self::verify_mu(pk, Some(&pk.A_hat()), &mu, sig)
2181    }
2182
2183    fn verify_init(pk: &PK, ctx: Option<&[u8]>) -> Result<Self, SignatureError> {
2184        Ok(Self {
2185            _phantom: Default::default(),
2186            mu_builder: MuBuilder::do_init(&pk.compute_tr(), ctx)?,
2187            signer_rnd: None,
2188            sk: None,
2189            seed: None,
2190            pk: Some(pk.clone()),
2191        })
2192    }
2193
2194    fn verify_update(&mut self, msg_chunk: &[u8]) {
2195        self.mu_builder.do_update(msg_chunk);
2196    }
2197
2198    fn verify_final(self, sig: &[u8]) -> Result<(), SignatureError> {
2199        let mu = self.mu_builder.do_final();
2200
2201        let pk: &PK = self
2202            .pk
2203            .as_ref()
2204            .ok_or(SignatureError::GenericError("No public key set on streaming verifier."))?;
2205        let sig: &[u8; SIG_LEN] = sig.try_into().map_err(|_| {
2206            SignatureError::LengthError("Signature value is not the correct length.")
2207        })?;
2208        Self::verify_mu(pk, Some(&pk.A_hat()), &mu, sig)
2209    }
2210}
2211
2212/// Implements parts of Algorithm 2 and Line 6 of Algorithm 7 of FIPS 204.
2213/// Provides a stateful version of [`MLDSATrait::compute_mu_from_pk`] and [`MLDSATrait::compute_mu_from_tr`]
2214/// that supports streaming
2215/// large to-be-signed messages.
2216///
2217/// Note: this struct is only exposed for "pure" ML-DSA and not for HashML-DSA because HashML-DSA
2218/// does not benefit from allowing external construction of the message representative mu.
2219/// The same behaviour can be obtained by computing the pre-hash `ph` with the appropriate hash function
2220/// and providing that to HashMLDSA via [`PHSigner::sign_ph`].
2221#[derive(Clone)]
2222pub struct MuBuilder {
2223    h: H,
2224}
2225
2226impl MuBuilder {
2227    /// Algorithm 7
2228    /// 6: 𝜇 ← H(BytesToBits(𝑡𝑟)||𝑀′, 64)
2229    pub fn compute_mu(
2230        tr: &[u8; 64],
2231        msg: &[u8],
2232        ctx: Option<&[u8]>,
2233    ) -> Result<[u8; 64], SignatureError> {
2234        let mut mu_builder = MuBuilder::do_init(&tr, ctx)?;
2235        mu_builder.do_update(msg);
2236        let mu = mu_builder.do_final();
2237
2238        Ok(mu)
2239    }
2240
2241    /// This function requires the public key hash `tr`, which can be computed from the public key
2242    /// using [`MLDSAPublicKeyTrait::compute_tr`].
2243    pub fn do_init(tr: &[u8; 64], ctx: Option<&[u8]>) -> Result<Self, SignatureError> {
2244        let ctx = match ctx {
2245            Some(ctx) => ctx,
2246            None => &[],
2247        };
2248
2249        // Algorithm 2
2250        // 1: if |𝑐𝑡𝑥| > 255 then
2251        if ctx.len() > 255 {
2252            return Err(SignatureError::LengthError("ctx value is longer than 255 bytes"));
2253        }
2254
2255        // Algorithm 7
2256        // 6: 𝜇 ← H(BytesToBits(𝑡𝑟)||𝑀', 64)
2257        let mut mb = Self { h: H::new() };
2258        mb.h.absorb(tr).expect("absorb before squeeze is infallible");
2259
2260        // Algorithm 2
2261        // 10: 𝑀′ ← BytesToBits(IntegerToBytes(0, 1) ∥ IntegerToBytes(|𝑐𝑡𝑥|, 1) ∥ 𝑐𝑡𝑥) ∥ 𝑀
2262        // all done together
2263        mb.h.absorb(&[0u8]).expect("absorb before squeeze is infallible");
2264        mb.h.absorb(&[ctx.len() as u8]).expect("absorb before squeeze is infallible");
2265        mb.h.absorb(ctx).expect("absorb before squeeze is infallible");
2266
2267        // now ready to absorb M
2268        Ok(mb)
2269    }
2270
2271    /// Stream a chunk of the message.
2272    pub fn do_update(&mut self, msg_chunk: &[u8]) {
2273        self.h.absorb(msg_chunk).expect("absorb before squeeze is infallible");
2274    }
2275
2276    /// Finalize and return the mu value.
2277    pub fn do_final(mut self) -> [u8; 64] {
2278        // Completion of
2279        // Algorithm 7
2280        // 6: 𝜇 ← H(BytesToBits(𝑡𝑟)||𝑀 ′, 64)
2281        let mut mu = [0u8; 64];
2282        self.h.squeeze_out(&mut mu);
2283
2284        mu
2285    }
2286}
2287
2288/// The length, in bytes, of a serialized state of a [`MuBuilder`] object.
2289pub const SUSPENDED_MU_BUILDER_STATE_LEN: usize = SUSPENDED_SHA3_STATE_LEN;
2290
2291/// If you are processing a large input message into ML-DSA and want to pause the operation
2292/// -- maybe while waiting for slow network IO), you'll need to use [`Suspendable`].
2293/// Serialization of the state of an in-progress ML-DSA instance is really just serialization
2294/// of the construction of the message representative mu, since no other part of the ML-DSA algorithm
2295/// has a pausable state.
2296// A [MuBuilder]'s (and by virtue, an ML-DSA instance's) entire mutable state is its inner SHAKE256 sponge,
2297// so serialization delegates directly to [SHAKE256]'s [SerializableState] impl.
2298impl Suspendable<SUSPENDED_SHA3_STATE_LEN> for MuBuilder {
2299    fn suspend(self) -> [u8; SUSPENDED_SHA3_STATE_LEN] {
2300        self.h.suspend()
2301    }
2302
2303    fn from_suspended(
2304        serialized_state: [u8; SUSPENDED_SHA3_STATE_LEN],
2305    ) -> Result<Self, SuspendableError> {
2306        Ok(MuBuilder { h: H::from_suspended(serialized_state)? })
2307    }
2308}