Skip to main content

quantaegis_slh_dsa/
lib.rs

1//! Pure-Rust, `#![no_std]`, `#![forbid(unsafe_code)]`, zero-external-dependency implementation of
2//! **NIST FIPS 205: Stateless Hash-Based Digital Signature Standard (SLH-DSA)**.
3//!
4//! Provides conservative, hash-only post-quantum security with zero reliance on lattice assumptions,
5//! implementing all six FIPS 205 SHAKE256 parameter sets:
6//! - [`SlhDsaShake128s`] / [`SlhDsaShake128f`] (NIST Security Category 1 — `pk = 32 B`, `sk = 64 B`, `sig = 7,856 / 17,088 B`)
7//! - [`SlhDsaShake192s`] / [`SlhDsaShake192f`] (NIST Security Category 3 — `pk = 48 B`, `sk = 96 B`, `sig = 16,224 / 35,664 B`)
8//! - [`SlhDsaShake256s`] / [`SlhDsaShake256f`] (NIST Security Category 5 — `pk = 64 B`, `sk = 128 B`, `sig = 29,792 / 49,856 B`)
9//!
10//! # Standards & Security Design
11//! - **Pure SLH-DSA** (FIPS 205 Algorithms 21–24) with domain-separation context strings (`|ctx| <= 255`).
12//! - **Hedged signing** (default via [`quantaegis_core::Signature::sign`]) and **deterministic signing**
13//!   (`opt_rand = PK.seed` via `sign_deterministic`).
14//! - **Zero external dependencies**, **zero heap allocation**, **zero hardware division instructions**.
15//! - Secret keys zeroize automatically on drop and redact in `Debug`.
16//!
17//! > **Note**: Pre-`1.0.0` software — an independent third-party cryptographic audit has not yet
18//! > been completed; please take this into account when using this crate. The project-wide maturity
19//! > stage is tracked in one place:
20//! > [SECURITY.md](https://github.com/PyRin-c/quantaegis/blob/main/SECURITY.md#maturity--production-readiness-status).
21
22#![no_std]
23#![forbid(unsafe_code)]
24// FIPS 205 SLH-DSA signatures are up to 49,856 bytes (`SLH-DSA-SHAKE-256f`) and are held inline
25// without `alloc` in `#![no_std]` mode; `sign_into` / `verify_bytes` are also provided for
26// zero-copy caller-owned buffers.
27#![allow(clippy::large_stack_arrays)]
28
29#[cfg(feature = "std")]
30extern crate std;
31
32mod address;
33mod fors;
34mod hypertree;
35pub mod params;
36mod shake_hash;
37mod slhdsa;
38mod wots;
39
40pub use params::MAX_CTX_LEN;
41
42use core::fmt;
43use quantaegis_core::{
44    CryptoRng, Error, Result, SecretBytes, Signature as SignatureTrait, Zeroize,
45};
46
47macro_rules! define_slh_dsa_variant {
48    (
49        mod_name: $mod_name:ident,
50        struct_name: $struct_name:ident,
51        params_mod: $params_mod:ident,
52        doc_name: $doc_name:literal,
53        sec_cat: $sec_cat:literal
54    ) => {
55        /// Typed keys, signatures, and constants for
56        #[doc = concat!("**", $doc_name, "** (NIST Security Category ", $sec_cat, ").")]
57        pub mod $mod_name {
58            use super::*;
59            use crate::params::$params_mod as P;
60
61            /// Security parameter `n` in bytes (`16`, `24`, or `32`).
62            pub const N: usize = P::N;
63            /// Public verifying key size in bytes (`2n`).
64            pub const PK_LEN: usize = P::PK_LEN;
65            /// Private signing key size in bytes (`4n`).
66            pub const SK_LEN: usize = P::SK_LEN;
67            /// Signature size in bytes.
68            pub const SIG_LEN: usize = P::SIG_LEN;
69
70            /// Public verifying key for
71            #[doc = concat!($doc_name, ".")]
72            #[derive(Clone, Eq, PartialEq)]
73            pub struct VerifyingKey {
74                bytes: [u8; PK_LEN],
75            }
76
77            impl VerifyingKey {
78                /// Parses a verifying key from its exact `2n`-byte encoding (`PK.seed || PK.root`).
79                pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
80                    if bytes.len() != PK_LEN {
81                        return Err(Error::InvalidLength {
82                            expected: PK_LEN,
83                            actual: bytes.len(),
84                        });
85                    }
86                    let mut arr = [0u8; PK_LEN];
87                    arr.copy_from_slice(bytes);
88                    Ok(Self { bytes: arr })
89                }
90
91                /// Constructs a verifying key from a fixed-size byte array.
92                #[inline]
93                pub const fn from_array(bytes: [u8; PK_LEN]) -> Self {
94                    Self { bytes }
95                }
96
97                /// Returns the canonical byte representation of the verifying key.
98                #[inline]
99                pub const fn as_bytes(&self) -> &[u8; PK_LEN] {
100                    &self.bytes
101                }
102
103                /// Returns an all-zero placeholder verifying key for in-place initialization.
104                #[inline]
105                pub const fn zeroed() -> Self {
106                    Self {
107                        bytes: [0u8; PK_LEN],
108                    }
109                }
110
111                /// Verifies `sig` over `msg` and domain-separation context `ctx` (`|ctx| <= 255`).
112                pub fn verify(&self, msg: &[u8], ctx: &[u8], sig: &Signature) -> Result<()> {
113                    self.verify_bytes(msg, ctx, &sig.bytes)
114                }
115
116                /// Verifies raw signature slice `sig` over `msg` and `ctx` without copying `sig` onto the stack.
117                pub fn verify_bytes(&self, msg: &[u8], ctx: &[u8], sig: &[u8]) -> Result<()> {
118                    crate::slhdsa::check_ctx(ctx)?;
119                    let sig_arr: &[u8; SIG_LEN] =
120                        sig.try_into().map_err(|_| Error::InvalidLength {
121                            expected: SIG_LEN,
122                            actual: sig.len(),
123                        })?;
124                    crate::slhdsa::verify_raw::<
125                        { P::N },
126                        { P::H },
127                        { P::D },
128                        { P::HP },
129                        { P::A },
130                        { P::K },
131                        { P::M },
132                        { P::WOTS_LEN },
133                        PK_LEN,
134                        SIG_LEN,
135                    >(&self.bytes, Some(ctx), msg, sig_arr)
136                }
137            }
138
139            impl fmt::Debug for VerifyingKey {
140                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141                    write!(f, "{}::VerifyingKey([{} bytes])", $doc_name, PK_LEN)
142                }
143            }
144
145            /// Private signing key for
146            #[doc = concat!($doc_name, " (automatically zeroized on drop, redacted in `Debug`).")]
147            pub struct SigningKey {
148                bytes: SecretBytes<SK_LEN>,
149            }
150
151            impl SigningKey {
152                /// Parses a signing key from its exact `4n`-byte encoding
153                /// (`SK.seed || SK.prf || PK.seed || PK.root`).
154                pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
155                    if bytes.len() != SK_LEN {
156                        return Err(Error::InvalidLength {
157                            expected: SK_LEN,
158                            actual: bytes.len(),
159                        });
160                    }
161                    let mut arr = [0u8; SK_LEN];
162                    arr.copy_from_slice(bytes);
163                    let secret = SecretBytes::new(arr);
164                    arr.zeroize();
165                    Ok(Self { bytes: secret })
166                }
167
168                /// Exposes the raw `4n`-byte signing key (handle with extreme care!).
169                #[inline]
170                pub fn expose_bytes(&self) -> &[u8; SK_LEN] {
171                    self.bytes.expose_secret()
172                }
173
174                /// Returns an all-zero placeholder signing key for in-place heap initialization
175                /// without stack-to-heap secret moves.
176                #[inline]
177                pub const fn zeroed() -> Self {
178                    Self {
179                        bytes: SecretBytes::new([0u8; SK_LEN]),
180                    }
181                }
182
183                /// Extracts the embedded `2n`-byte verifying key (`PK.seed || PK.root`).
184                pub fn verifying_key(&self) -> VerifyingKey {
185                    let mut pk = [0u8; PK_LEN];
186                    pk.copy_from_slice(&self.bytes.expose_secret()[2 * N..4 * N]);
187                    VerifyingKey { bytes: pk }
188                }
189
190                /// Signs `msg` with context `ctx` directly into caller-owned `sig_out` (hedged mode).
191                pub fn sign_into<R: CryptoRng + ?Sized>(
192                    &self,
193                    msg: &[u8],
194                    ctx: &[u8],
195                    rng: &mut R,
196                    sig_out: &mut [u8; SIG_LEN],
197                ) -> Result<()> {
198                    crate::slhdsa::check_ctx(ctx)?;
199                    let mut opt_rand = SecretBytes::new([0u8; N]);
200                    rng.try_fill_bytes(opt_rand.expose_secret_mut())?;
201                    crate::slhdsa::sign_into::<
202                        { P::N },
203                        { P::H },
204                        { P::D },
205                        { P::HP },
206                        { P::A },
207                        { P::K },
208                        { P::M },
209                        { P::WOTS_LEN },
210                        SK_LEN,
211                        SIG_LEN,
212                    >(
213                        self.bytes.expose_secret(),
214                        Some(ctx),
215                        msg,
216                        Some(opt_rand.expose_secret()),
217                        sig_out,
218                    );
219                    Ok(())
220                }
221
222                /// Signs `msg` with context `ctx` using fresh randomness (hedged mode, FIPS 205 Alg. 22).
223                pub fn sign<R: CryptoRng + ?Sized>(
224                    &self,
225                    msg: &[u8],
226                    ctx: &[u8],
227                    rng: &mut R,
228                ) -> Result<Signature> {
229                    let mut sig = [0u8; SIG_LEN];
230                    self.sign_into(msg, ctx, rng, &mut sig)?;
231                    Ok(Signature { bytes: sig })
232                }
233
234                /// Signs `msg` with context `ctx` directly into `sig_out` in deterministic mode (`opt_rand = PK.seed`).
235                pub fn sign_deterministic_into(
236                    &self,
237                    msg: &[u8],
238                    ctx: &[u8],
239                    sig_out: &mut [u8; SIG_LEN],
240                ) -> Result<()> {
241                    crate::slhdsa::check_ctx(ctx)?;
242                    crate::slhdsa::sign_into::<
243                        { P::N },
244                        { P::H },
245                        { P::D },
246                        { P::HP },
247                        { P::A },
248                        { P::K },
249                        { P::M },
250                        { P::WOTS_LEN },
251                        SK_LEN,
252                        SIG_LEN,
253                    >(self.bytes.expose_secret(), Some(ctx), msg, None, sig_out);
254                    Ok(())
255                }
256
257                /// Signs `msg` with context `ctx` in deterministic mode (`opt_rand = PK.seed`).
258                pub fn sign_deterministic(&self, msg: &[u8], ctx: &[u8]) -> Result<Signature> {
259                    let mut sig = [0u8; SIG_LEN];
260                    self.sign_deterministic_into(msg, ctx, &mut sig)?;
261                    Ok(Signature { bytes: sig })
262                }
263            }
264
265            impl Zeroize for SigningKey {
266                #[inline]
267                fn zeroize(&mut self) {
268                    self.bytes.zeroize();
269                }
270            }
271
272            impl fmt::Debug for SigningKey {
273                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274                    write!(f, "{}::SigningKey([REDACTED])", $doc_name)
275                }
276            }
277
278            /// Digital signature for
279            #[doc = concat!($doc_name, ".")]
280            #[derive(Clone, Eq, PartialEq)]
281            pub struct Signature {
282                bytes: [u8; SIG_LEN],
283            }
284
285            impl Signature {
286                /// Parses a signature from its exact byte encoding.
287                pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
288                    if bytes.len() != SIG_LEN {
289                        return Err(Error::InvalidLength {
290                            expected: SIG_LEN,
291                            actual: bytes.len(),
292                        });
293                    }
294                    let mut arr = [0u8; SIG_LEN];
295                    arr.copy_from_slice(bytes);
296                    Ok(Self { bytes: arr })
297                }
298
299                /// Constructs a signature from a fixed-size byte array.
300                #[inline]
301                pub const fn from_array(bytes: [u8; SIG_LEN]) -> Self {
302                    Self { bytes }
303                }
304
305                /// Returns the canonical byte representation of the signature.
306                #[inline]
307                pub const fn as_bytes(&self) -> &[u8; SIG_LEN] {
308                    &self.bytes
309                }
310            }
311
312            impl fmt::Debug for Signature {
313                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
314                    write!(f, "{}::Signature([{} bytes])", $doc_name, SIG_LEN)
315                }
316            }
317
318            #[cfg(feature = "hazmat")]
319            pub(crate) fn keygen_raw(
320                sk_seed: &[u8; N],
321                sk_prf: &[u8; N],
322                pk_seed: &[u8; N],
323            ) -> (VerifyingKey, SigningKey) {
324                let mut pair = (VerifyingKey::zeroed(), SigningKey::zeroed());
325                keygen_raw_into(sk_seed, sk_prf, pk_seed, &mut pair.0, &mut pair.1);
326                pair
327            }
328
329            pub(crate) fn keygen_raw_into(
330                sk_seed: &[u8; N],
331                sk_prf: &[u8; N],
332                pk_seed: &[u8; N],
333                vk_out: &mut VerifyingKey,
334                sk_out: &mut SigningKey,
335            ) {
336                crate::slhdsa::keygen_internal_into::<
337                    { P::N },
338                    { P::D },
339                    { P::HP },
340                    { P::WOTS_LEN },
341                    PK_LEN,
342                    SK_LEN,
343                >(
344                    sk_seed,
345                    sk_prf,
346                    pk_seed,
347                    &mut vk_out.bytes,
348                    sk_out.bytes.expose_secret_mut(),
349                );
350            }
351
352            /// Low-level FIPS 205 internal algorithms (`Algorithms 18–20`) for NIST ACVP KAT
353            /// validation (requires Cargo feature `hazmat`).
354            #[cfg(feature = "hazmat")]
355            pub mod hazmat {
356                use super::*;
357
358                /// FIPS 205 Algorithm 18: `slh_keygen_internal(SK.seed, SK.prf, PK.seed)`.
359                pub fn keygen_internal(
360                    sk_seed: &[u8; N],
361                    sk_prf: &[u8; N],
362                    pk_seed: &[u8; N],
363                ) -> (VerifyingKey, SigningKey) {
364                    keygen_raw(sk_seed, sk_prf, pk_seed)
365                }
366
367                /// FIPS 205 Algorithm 19: `slh_sign_internal(M', SK, opt_rand)`.
368                pub fn sign_internal(
369                    sk: &SigningKey,
370                    msg_prime: &[u8],
371                    opt_rand: Option<&[u8; N]>,
372                ) -> Signature {
373                    let mut sig = [0u8; SIG_LEN];
374                    crate::slhdsa::sign_into::<
375                        { P::N },
376                        { P::H },
377                        { P::D },
378                        { P::HP },
379                        { P::A },
380                        { P::K },
381                        { P::M },
382                        { P::WOTS_LEN },
383                        SK_LEN,
384                        SIG_LEN,
385                    >(sk.expose_bytes(), None, msg_prime, opt_rand, &mut sig);
386                    Signature { bytes: sig }
387                }
388
389                /// FIPS 205 Algorithm 20: `slh_verify_internal(M', SIG, PK)`.
390                pub fn verify_internal(
391                    vk: &VerifyingKey,
392                    msg_prime: &[u8],
393                    sig: &Signature,
394                ) -> Result<()> {
395                    crate::slhdsa::verify_raw::<
396                        { P::N },
397                        { P::H },
398                        { P::D },
399                        { P::HP },
400                        { P::A },
401                        { P::K },
402                        { P::M },
403                        { P::WOTS_LEN },
404                        PK_LEN,
405                        SIG_LEN,
406                    >(vk.as_bytes(), None, msg_prime, sig.as_bytes())
407                }
408            }
409        }
410
411        /// Marker type implementing [`quantaegis_core::Signature`] for
412        #[doc = concat!("**", $doc_name, "** (NIST Security Category ", $sec_cat, ").")]
413        pub struct $struct_name;
414
415        impl $struct_name {
416            /// Generates a fresh key pair directly into caller-owned storage and volatile-zeroizes
417            /// stack temporaries (`FIPS 205, Algorithm 21`).
418            pub fn keygen_into<R: CryptoRng + ?Sized>(
419                rng: &mut R,
420                vk_out: &mut $mod_name::VerifyingKey,
421                sk_out: &mut $mod_name::SigningKey,
422            ) -> Result<()> {
423                let mut sk_seed = SecretBytes::new([0u8; $mod_name::N]);
424                let mut sk_prf = SecretBytes::new([0u8; $mod_name::N]);
425                let mut pk_seed = [0u8; $mod_name::N];
426                rng.try_fill_bytes(sk_seed.expose_secret_mut())?;
427                rng.try_fill_bytes(sk_prf.expose_secret_mut())?;
428                rng.try_fill_bytes(&mut pk_seed)?;
429                $mod_name::keygen_raw_into(
430                    sk_seed.expose_secret(),
431                    sk_prf.expose_secret(),
432                    &pk_seed,
433                    vk_out,
434                    sk_out,
435                );
436                Ok(())
437            }
438
439            /// Signs `msg` with context `ctx` in deterministic mode (`opt_rand = PK.seed`).
440            pub fn sign_deterministic(
441                sk: &$mod_name::SigningKey,
442                msg: &[u8],
443                ctx: &[u8],
444            ) -> Result<$mod_name::Signature> {
445                sk.sign_deterministic(msg, ctx)
446            }
447        }
448
449        impl SignatureTrait for $struct_name {
450            type VerifyingKey = $mod_name::VerifyingKey;
451            type SigningKey = $mod_name::SigningKey;
452            type Sig = $mod_name::Signature;
453
454            /// Generates a fresh key pair by value; FIPS/zeroization-critical callers should prefer
455            /// [`Self::keygen_into`] to avoid safe-Rust return-slot staging copies.
456            fn keygen<R: CryptoRng + ?Sized>(
457                rng: &mut R,
458            ) -> Result<(Self::VerifyingKey, Self::SigningKey)> {
459                let mut res = Ok((
460                    $mod_name::VerifyingKey::zeroed(),
461                    $mod_name::SigningKey::zeroed(),
462                ));
463                if let Ok((ref mut vk, ref mut sk)) = res
464                    && let Err(e) = Self::keygen_into(rng, vk, sk)
465                {
466                    res = Err(e);
467                }
468                res
469            }
470
471            fn sign<R: CryptoRng + ?Sized>(
472                sk: &Self::SigningKey,
473                msg: &[u8],
474                ctx: &[u8],
475                rng: &mut R,
476            ) -> Result<Self::Sig> {
477                sk.sign(msg, ctx, rng)
478            }
479
480            fn verify(
481                vk: &Self::VerifyingKey,
482                msg: &[u8],
483                ctx: &[u8],
484                sig: &Self::Sig,
485            ) -> Result<()> {
486                vk.verify(msg, ctx, sig)
487            }
488        }
489    };
490}
491
492define_slh_dsa_variant! {
493    mod_name: slh_dsa_shake_128s,
494    struct_name: SlhDsaShake128s,
495    params_mod: shake_128s,
496    doc_name: "SLH-DSA-SHAKE-128s",
497    sec_cat: "1"
498}
499
500define_slh_dsa_variant! {
501    mod_name: slh_dsa_shake_128f,
502    struct_name: SlhDsaShake128f,
503    params_mod: shake_128f,
504    doc_name: "SLH-DSA-SHAKE-128f",
505    sec_cat: "1"
506}
507
508define_slh_dsa_variant! {
509    mod_name: slh_dsa_shake_192s,
510    struct_name: SlhDsaShake192s,
511    params_mod: shake_192s,
512    doc_name: "SLH-DSA-SHAKE-192s",
513    sec_cat: "3"
514}
515
516define_slh_dsa_variant! {
517    mod_name: slh_dsa_shake_192f,
518    struct_name: SlhDsaShake192f,
519    params_mod: shake_192f,
520    doc_name: "SLH-DSA-SHAKE-192f",
521    sec_cat: "3"
522}
523
524define_slh_dsa_variant! {
525    mod_name: slh_dsa_shake_256s,
526    struct_name: SlhDsaShake256s,
527    params_mod: shake_256s,
528    doc_name: "SLH-DSA-SHAKE-256s",
529    sec_cat: "5"
530}
531
532define_slh_dsa_variant! {
533    mod_name: slh_dsa_shake_256f,
534    struct_name: SlhDsaShake256f,
535    params_mod: shake_256f,
536    doc_name: "SLH-DSA-SHAKE-256f",
537    sec_cat: "5"
538}
539
540#[cfg(test)]
541mod rng_failure_tests {
542    use super::*;
543    use quantaegis_core::{CryptoRng, Error, Result, Signature as SignatureTrait};
544
545    struct FailAfterNCalls {
546        succeed_calls: usize,
547        calls: usize,
548    }
549
550    impl CryptoRng for FailAfterNCalls {
551        fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<()> {
552            self.calls += 1;
553            dest.fill(0x5A);
554            if self.calls > self.succeed_calls {
555                return Err(Error::RngFailure);
556            }
557            Ok(())
558        }
559    }
560
561    #[test]
562    fn keygen_propagates_rng_failure_on_intermediate_seed_calls() {
563        for succeed_calls in [0usize, 1, 2] {
564            let mut rng = FailAfterNCalls {
565                succeed_calls,
566                calls: 0,
567            };
568            assert!(matches!(
569                SlhDsaShake128f::keygen(&mut rng),
570                Err(Error::RngFailure)
571            ));
572            assert_eq!(rng.calls, succeed_calls + 1);
573        }
574    }
575}