1#![no_std]
25#![forbid(unsafe_code)]
26
27#[cfg(feature = "std")]
28extern crate std;
29
30mod field;
31mod mldsa;
32mod ntt;
33mod packing;
34pub mod params;
35mod poly;
36mod rounding;
37mod sampling;
38
39pub use params::{MAX_CTX_LEN, MU_LEN, RND_LEN, SEED_LEN};
40
41use core::fmt;
42use quantaegis_core::{
43 CryptoRng, Error, Result, SecretBytes, Signature as SignatureTrait, Zeroize,
44};
45use quantaegis_sha3::Shake256;
46
47pub struct MuHasher {
53 xof: Shake256,
54}
55
56impl MuHasher {
57 pub fn new(tr: &[u8; params::TR_LEN], ctx: &[u8]) -> Result<Self> {
60 if ctx.len() > MAX_CTX_LEN {
61 return Err(Error::ContextTooLong {
62 max: MAX_CTX_LEN,
63 actual: ctx.len(),
64 });
65 }
66 let mut xof = Shake256::new();
67 xof.update(tr);
68 #[allow(clippy::cast_possible_truncation)]
69 let prefix = [0x00u8, ctx.len() as u8];
70 xof.update(&prefix);
71 xof.update(ctx);
72 Ok(Self { xof })
73 }
74
75 #[inline]
77 pub fn update(&mut self, chunk: &[u8]) {
78 self.xof.update(chunk);
79 }
80
81 pub fn finalize(self) -> [u8; MU_LEN] {
83 let mut mu = [0u8; MU_LEN];
84 self.xof.finalize_xof().squeeze(&mut mu);
85 mu
86 }
87}
88
89impl fmt::Debug for MuHasher {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 f.write_str("MuHasher(..)")
92 }
93}
94
95macro_rules! define_ml_dsa_variant {
97 (
98 mod_name: $mod_name:ident,
99 struct_name: $struct_name:ident,
100 params_mod: $params_mod:ident,
101 doc_name: $doc_name:literal,
102 sec_cat: $sec_cat:literal
103 ) => {
104 #[doc = concat!("**", $doc_name, "** (NIST Security Category ", $sec_cat, ").")]
106 pub mod $mod_name {
107 use super::*;
108 use crate::params::$params_mod as P;
109
110 pub const PK_LEN: usize = P::PK_LEN;
112 pub const SK_LEN: usize = P::SK_LEN;
114 pub const SIG_LEN: usize = P::SIG_LEN;
116 pub const SEED_LEN: usize = crate::params::SEED_LEN;
118
119 #[doc = concat!($doc_name, ".")]
121 #[derive(Clone, Eq, PartialEq)]
122 pub struct VerifyingKey {
123 bytes: [u8; PK_LEN],
124 }
125
126 impl VerifyingKey {
127 pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
129 if bytes.len() != PK_LEN {
130 return Err(Error::InvalidLength {
131 expected: PK_LEN,
132 actual: bytes.len(),
133 });
134 }
135 let mut arr = [0u8; PK_LEN];
136 arr.copy_from_slice(bytes);
137 Ok(Self { bytes: arr })
138 }
139
140 #[inline]
142 pub const fn from_array(bytes: [u8; PK_LEN]) -> Self {
143 Self { bytes }
144 }
145
146 #[inline]
148 pub const fn as_bytes(&self) -> &[u8; PK_LEN] {
149 &self.bytes
150 }
151
152 #[inline]
154 pub const fn zeroed() -> Self {
155 Self {
156 bytes: [0u8; PK_LEN],
157 }
158 }
159
160 pub fn tr(&self) -> [u8; 64] {
162 crate::mldsa::compute_tr(&self.bytes)
163 }
164
165 pub fn mu_hasher(&self, ctx: &[u8]) -> Result<MuHasher> {
167 MuHasher::new(&self.tr(), ctx)
168 }
169
170 pub fn verify_mu(&self, mu: &[u8; MU_LEN], sig: &Signature) -> Result<()> {
172 crate::mldsa::verify_mu_internal::<
173 { P::K },
174 { P::L },
175 { P::TAU },
176 { P::BETA },
177 { P::GAMMA1 },
178 { P::GAMMA2 },
179 { P::OMEGA },
180 { P::C_TILDE_LEN },
181 { P::W1_LEN },
182 PK_LEN,
183 SIG_LEN,
184 >(&self.bytes, mu, &sig.bytes)
185 }
186
187 pub fn verify(&self, msg: &[u8], ctx: &[u8], sig: &Signature) -> Result<()> {
189 let tr = self.tr();
190 let mu = crate::mldsa::compute_pure_mu(&tr, msg, ctx)?;
191 crate::mldsa::verify_mu_internal::<
192 { P::K },
193 { P::L },
194 { P::TAU },
195 { P::BETA },
196 { P::GAMMA1 },
197 { P::GAMMA2 },
198 { P::OMEGA },
199 { P::C_TILDE_LEN },
200 { P::W1_LEN },
201 PK_LEN,
202 SIG_LEN,
203 >(&self.bytes, &mu, &sig.bytes)
204 }
205 }
206
207 impl fmt::Debug for VerifyingKey {
208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209 write!(f, "{}::VerifyingKey([{} bytes])", $doc_name, PK_LEN)
210 }
211 }
212
213 #[doc = concat!($doc_name, " (automatically zeroized on drop, redacted in `Debug`).")]
215 pub struct SigningKey {
216 bytes: SecretBytes<SK_LEN>,
217 }
218
219 impl SigningKey {
220 pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
224 if bytes.len() != SK_LEN {
225 return Err(Error::InvalidLength {
226 expected: SK_LEN,
227 actual: bytes.len(),
228 });
229 }
230 let mut arr = [0u8; SK_LEN];
231 arr.copy_from_slice(bytes);
232 let res =
233 crate::mldsa::validate_sk::<{ P::K }, { P::L }, { P::ETA }, SK_LEN>(&arr);
234 if let Err(e) = res {
235 arr.zeroize();
236 return Err(e);
237 }
238 let secret = SecretBytes::new(arr);
239 arr.zeroize();
240 Ok(Self { bytes: secret })
241 }
242
243 #[inline]
245 pub fn expose_bytes(&self) -> &[u8; SK_LEN] {
246 self.bytes.expose_secret()
247 }
248
249 #[inline]
252 pub const fn zeroed() -> Self {
253 Self {
254 bytes: SecretBytes::new([0u8; SK_LEN]),
255 }
256 }
257
258 pub fn tr(&self) -> [u8; 64] {
260 crate::mldsa::sk_tr(self.bytes.expose_secret())
261 }
262
263 pub fn mu_hasher(&self, ctx: &[u8]) -> Result<MuHasher> {
265 MuHasher::new(&self.tr(), ctx)
266 }
267
268 pub fn sign_mu<R: CryptoRng + ?Sized>(
270 &self,
271 mu: &[u8; MU_LEN],
272 rng: &mut R,
273 ) -> Result<Signature> {
274 let mut rnd = SecretBytes::new([0u8; RND_LEN]);
275 rng.try_fill_bytes(rnd.expose_secret_mut())?;
276 sign_mu_raw(self, mu, rnd.expose_secret())
277 }
278
279 pub fn sign_mu_deterministic(&self, mu: &[u8; MU_LEN]) -> Result<Signature> {
281 let rnd = [0u8; RND_LEN];
282 sign_mu_raw(self, mu, &rnd)
283 }
284
285 pub fn sign_into<R: CryptoRng + ?Sized>(
289 &self,
290 msg: &[u8],
291 ctx: &[u8],
292 rng: &mut R,
293 sig_out: &mut [u8],
294 ) -> Result<()> {
295 let actual = sig_out.len();
296 let out_arr: &mut [u8; SIG_LEN] =
297 sig_out.try_into().map_err(|_| Error::InvalidLength {
298 expected: SIG_LEN,
299 actual,
300 })?;
301 let tr = self.tr();
302 let mu = crate::mldsa::compute_pure_mu(&tr, msg, ctx)?;
303 let mut rnd = SecretBytes::new([0u8; RND_LEN]);
304 rng.try_fill_bytes(rnd.expose_secret_mut())?;
305 crate::mldsa::sign_mu_internal_into::<
306 { P::K },
307 { P::L },
308 { P::ETA },
309 { P::TAU },
310 { P::BETA },
311 { P::GAMMA1 },
312 { P::GAMMA2 },
313 { P::OMEGA },
314 { P::C_TILDE_LEN },
315 { P::W1_LEN },
316 SK_LEN,
317 SIG_LEN,
318 >(
319 self.bytes.expose_secret(),
320 &mu,
321 rnd.expose_secret(),
322 out_arr,
323 )
324 }
325
326 pub fn sign<R: CryptoRng + ?Sized>(
329 &self,
330 msg: &[u8],
331 ctx: &[u8],
332 rng: &mut R,
333 ) -> Result<Signature> {
334 let mut bytes = [0u8; SIG_LEN];
335 self.sign_into(msg, ctx, rng, &mut bytes)?;
336 Ok(Signature { bytes })
337 }
338
339 pub fn sign_deterministic(&self, msg: &[u8], ctx: &[u8]) -> Result<Signature> {
341 let rnd = [0u8; RND_LEN];
342 let tr = self.tr();
343 let mu = crate::mldsa::compute_pure_mu(&tr, msg, ctx)?;
344 let bytes = crate::mldsa::sign_mu_internal::<
345 { P::K },
346 { P::L },
347 { P::ETA },
348 { P::TAU },
349 { P::BETA },
350 { P::GAMMA1 },
351 { P::GAMMA2 },
352 { P::OMEGA },
353 { P::C_TILDE_LEN },
354 { P::W1_LEN },
355 SK_LEN,
356 SIG_LEN,
357 >(self.bytes.expose_secret(), &mu, &rnd)?;
358 Ok(Signature { bytes })
359 }
360 }
361
362 impl Zeroize for SigningKey {
363 #[inline]
364 fn zeroize(&mut self) {
365 self.bytes.zeroize();
366 }
367 }
368
369 impl fmt::Debug for SigningKey {
370 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371 write!(f, "{}::SigningKey([REDACTED])", $doc_name)
372 }
373 }
374
375 #[doc = concat!($doc_name, ".")]
377 #[derive(Clone, Eq, PartialEq)]
378 pub struct Signature {
379 bytes: [u8; SIG_LEN],
380 }
381
382 impl Signature {
383 pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
385 if bytes.len() != SIG_LEN {
386 return Err(Error::InvalidLength {
387 expected: SIG_LEN,
388 actual: bytes.len(),
389 });
390 }
391 let mut arr = [0u8; SIG_LEN];
392 arr.copy_from_slice(bytes);
393 Ok(Self { bytes: arr })
394 }
395
396 #[inline]
398 pub const fn from_array(bytes: [u8; SIG_LEN]) -> Self {
399 Self { bytes }
400 }
401
402 #[inline]
404 pub const fn as_bytes(&self) -> &[u8; SIG_LEN] {
405 &self.bytes
406 }
407 }
408
409 impl fmt::Debug for Signature {
410 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411 write!(f, "{}::Signature([{} bytes])", $doc_name, SIG_LEN)
412 }
413 }
414
415 pub(crate) fn keygen_raw(xi: &[u8; SEED_LEN]) -> (VerifyingKey, SigningKey) {
416 let mut pair = (VerifyingKey::zeroed(), SigningKey::zeroed());
417 keygen_raw_into(xi, &mut pair.0, &mut pair.1);
418 pair
419 }
420
421 pub(crate) fn keygen_raw_into(
422 xi: &[u8; SEED_LEN],
423 vk_out: &mut VerifyingKey,
424 sk_out: &mut SigningKey,
425 ) {
426 crate::mldsa::keygen_internal_into::<
427 { P::K },
428 { P::L },
429 { P::ETA },
430 PK_LEN,
431 SK_LEN,
432 >(xi, &mut vk_out.bytes, sk_out.bytes.expose_secret_mut());
433 }
434
435 pub(crate) fn sign_mu_raw(
436 sk: &SigningKey,
437 mu: &[u8; MU_LEN],
438 rnd: &[u8; RND_LEN],
439 ) -> Result<Signature> {
440 let bytes = crate::mldsa::sign_mu_internal::<
441 { P::K },
442 { P::L },
443 { P::ETA },
444 { P::TAU },
445 { P::BETA },
446 { P::GAMMA1 },
447 { P::GAMMA2 },
448 { P::OMEGA },
449 { P::C_TILDE_LEN },
450 { P::W1_LEN },
451 SK_LEN,
452 SIG_LEN,
453 >(sk.expose_bytes(), mu, rnd)?;
454 Ok(Signature { bytes })
455 }
456
457 #[cfg(feature = "hazmat")]
460 pub mod hazmat {
461 use super::*;
462
463 pub fn keygen_internal(xi: &[u8; SEED_LEN]) -> (VerifyingKey, SigningKey) {
465 keygen_raw(xi)
466 }
467
468 pub fn sign_internal(
470 sk: &SigningKey,
471 msg_prime: &[u8],
472 rnd: &[u8; RND_LEN],
473 ) -> Result<Signature> {
474 let tr = sk.tr();
475 let mu = crate::mldsa::compute_internal_mu(&tr, msg_prime);
476 sign_mu_internal(sk, &mu, rnd)
477 }
478
479 pub fn sign_mu_internal(
482 sk: &SigningKey,
483 mu: &[u8; MU_LEN],
484 rnd: &[u8; RND_LEN],
485 ) -> Result<Signature> {
486 sign_mu_raw(sk, mu, rnd)
487 }
488
489 pub fn verify_internal(
491 vk: &VerifyingKey,
492 msg_prime: &[u8],
493 sig: &Signature,
494 ) -> Result<()> {
495 let tr = vk.tr();
496 let mu = crate::mldsa::compute_internal_mu(&tr, msg_prime);
497 verify_mu_internal(vk, &mu, sig)
498 }
499
500 pub fn verify_mu_internal(
502 vk: &VerifyingKey,
503 mu: &[u8; MU_LEN],
504 sig: &Signature,
505 ) -> Result<()> {
506 crate::mldsa::verify_mu_internal::<
507 { P::K },
508 { P::L },
509 { P::TAU },
510 { P::BETA },
511 { P::GAMMA1 },
512 { P::GAMMA2 },
513 { P::OMEGA },
514 { P::C_TILDE_LEN },
515 { P::W1_LEN },
516 PK_LEN,
517 SIG_LEN,
518 >(vk.as_bytes(), mu, sig.as_bytes())
519 }
520 }
521 }
522
523 #[doc = concat!("**", $doc_name, "** (NIST Security Category ", $sec_cat, ").")]
525 pub struct $struct_name;
526
527 impl $struct_name {
528 pub fn from_seed(
535 seed: &[u8; SEED_LEN],
536 ) -> ($mod_name::VerifyingKey, $mod_name::SigningKey) {
537 $mod_name::keygen_raw(seed)
538 }
539
540 pub fn keygen_into<R: CryptoRng + ?Sized>(
543 rng: &mut R,
544 vk_out: &mut $mod_name::VerifyingKey,
545 sk_out: &mut $mod_name::SigningKey,
546 ) -> Result<()> {
547 let mut xi = SecretBytes::new([0u8; SEED_LEN]);
548 rng.try_fill_bytes(xi.expose_secret_mut())?;
549 $mod_name::keygen_raw_into(xi.expose_secret(), vk_out, sk_out);
550 Ok(())
551 }
552
553 pub fn sign_deterministic(
555 sk: &$mod_name::SigningKey,
556 msg: &[u8],
557 ctx: &[u8],
558 ) -> Result<$mod_name::Signature> {
559 sk.sign_deterministic(msg, ctx)
560 }
561
562 pub fn sign_mu<R: CryptoRng + ?Sized>(
564 sk: &$mod_name::SigningKey,
565 mu: &[u8; MU_LEN],
566 rng: &mut R,
567 ) -> Result<$mod_name::Signature> {
568 sk.sign_mu(mu, rng)
569 }
570
571 pub fn sign_mu_deterministic(
573 sk: &$mod_name::SigningKey,
574 mu: &[u8; MU_LEN],
575 ) -> Result<$mod_name::Signature> {
576 sk.sign_mu_deterministic(mu)
577 }
578
579 pub fn verify_mu(
581 vk: &$mod_name::VerifyingKey,
582 mu: &[u8; MU_LEN],
583 sig: &$mod_name::Signature,
584 ) -> Result<()> {
585 vk.verify_mu(mu, sig)
586 }
587 }
588
589 impl SignatureTrait for $struct_name {
590 type VerifyingKey = $mod_name::VerifyingKey;
591 type SigningKey = $mod_name::SigningKey;
592 type Sig = $mod_name::Signature;
593
594 fn keygen<R: CryptoRng + ?Sized>(
597 rng: &mut R,
598 ) -> Result<(Self::VerifyingKey, Self::SigningKey)> {
599 let mut res = Ok((
600 $mod_name::VerifyingKey::zeroed(),
601 $mod_name::SigningKey::zeroed(),
602 ));
603 if let Ok((ref mut vk, ref mut sk)) = res
604 && let Err(e) = Self::keygen_into(rng, vk, sk)
605 {
606 res = Err(e);
607 }
608 res
609 }
610
611 fn sign<R: CryptoRng + ?Sized>(
612 sk: &Self::SigningKey,
613 msg: &[u8],
614 ctx: &[u8],
615 rng: &mut R,
616 ) -> Result<Self::Sig> {
617 sk.sign(msg, ctx, rng)
618 }
619
620 fn verify(
621 vk: &Self::VerifyingKey,
622 msg: &[u8],
623 ctx: &[u8],
624 sig: &Self::Sig,
625 ) -> Result<()> {
626 vk.verify(msg, ctx, sig)
627 }
628 }
629 };
630}
631
632define_ml_dsa_variant! {
633 mod_name: ml_dsa_44,
634 struct_name: MlDsa44,
635 params_mod: p44,
636 doc_name: "ML-DSA-44",
637 sec_cat: "2"
638}
639
640define_ml_dsa_variant! {
641 mod_name: ml_dsa_65,
642 struct_name: MlDsa65,
643 params_mod: p65,
644 doc_name: "ML-DSA-65",
645 sec_cat: "3"
646}
647
648define_ml_dsa_variant! {
649 mod_name: ml_dsa_87,
650 struct_name: MlDsa87,
651 params_mod: p87,
652 doc_name: "ML-DSA-87",
653 sec_cat: "5"
654}
655
656#[cfg(test)]
657#[allow(clippy::expect_used)]
658mod streaming_mu_tests {
659 use super::*;
660
661 #[test]
662 fn streaming_mu_hasher_matches_oneshot_pure_ml_dsa() {
663 let seed = [0x42u8; SEED_LEN];
664 let (vk, sk) = MlDsa65::from_seed(&seed);
665 let msg = [0xABu8; 777];
666 let ctx = b"stream-ctx";
667
668 let mut signer_hasher = sk.mu_hasher(ctx).expect("valid ctx");
669 signer_hasher.update(&msg[..1]);
670 signer_hasher.update(&msg[1..137]);
671 signer_hasher.update(&msg[137..500]);
672 signer_hasher.update(&msg[500..]);
673 let signer_mu = signer_hasher.finalize();
674
675 let mut verifier_hasher = vk.mu_hasher(ctx).expect("valid ctx");
676 verifier_hasher.update(&msg[..333]);
677 verifier_hasher.update(&msg[333..]);
678 let verifier_mu = verifier_hasher.finalize();
679 assert_eq!(signer_mu, verifier_mu);
680
681 let sig_oneshot = MlDsa65::sign_deterministic(&sk, &msg, ctx).expect("oneshot sign");
682 let sig_mu = MlDsa65::sign_mu_deterministic(&sk, &signer_mu).expect("mu sign");
683 assert_eq!(sig_oneshot, sig_mu);
684
685 assert!(MlDsa65::verify(&vk, &msg, ctx, &sig_mu).is_ok());
686 assert!(MlDsa65::verify_mu(&vk, &verifier_mu, &sig_oneshot).is_ok());
687
688 let mut bad_mu = verifier_mu;
689 bad_mu[0] ^= 0x01;
690 assert_eq!(
691 MlDsa65::verify_mu(&vk, &bad_mu, &sig_oneshot),
692 Err(Error::InvalidSignature)
693 );
694 assert!(vk.mu_hasher(&[0u8; 256]).is_err());
695 }
696
697 #[test]
698 fn sign_rejects_overlong_context_before_consuming_rng() {
699 struct CountingFailRng {
700 calls: usize,
701 }
702
703 impl CryptoRng for CountingFailRng {
704 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<()> {
705 self.calls += 1;
706 dest.fill(0xA5);
707 Err(Error::RngFailure)
708 }
709 }
710
711 let seed = [0x42u8; SEED_LEN];
712 let (_vk, sk) = MlDsa65::from_seed(&seed);
713 let mut rng = CountingFailRng { calls: 0 };
714 let res = sk.sign(b"msg", &[0u8; 256], &mut rng);
715 assert_eq!(
716 res,
717 Err(Error::ContextTooLong {
718 max: 255,
719 actual: 256,
720 })
721 );
722 assert_eq!(rng.calls, 0);
723 }
724}