krypteia-quantica 0.2.0

Pure-Rust post-quantum cryptography: FIPS 203 ML-KEM, FIPS 204 ML-DSA, and FIPS 205 SLH-DSA. First-order arithmetic masking, shuffled NTT, FORS recompute-and-compare redundancy, constant-time rejection sampling. Targets embedded (no_std), STM32 M0/M4/M33, ESP32-C3 RISC-V. Zero runtime dependencies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Cédric Mesnil <cslashm@pm.me>

// The key / signature / ciphertext types are fixed-size byte containers;
// `len()` returns a compile-time constant (`Params::*_LEN`), so `is_empty()`
// (always `false`) carries no meaning. Documented allow per CLAUDE.md §6.
#![allow(clippy::len_without_is_empty)]

//! SLH-DSA: Stateless Hash-Based Digital Signature Standard (FIPS 205).
//!
//! This crate provides a pure-Rust implementation of SLH-DSA (formerly known as SPHINCS+),
//! a post-quantum digital signature scheme standardized in [FIPS 205]. SLH-DSA is purely
//! hash-based: its security relies only on the properties of cryptographic hash functions,
//! with no algebraic structure (lattices, codes, etc.) that could be exploited by quantum
//! or classical algorithms beyond generic attacks.
//!
//! # Architecture
//!
//! SLH-DSA is built from a hierarchy of hash-based primitives:
//!
//! 1. **WOTS+** -- A one-time signature scheme that signs a single n-byte message using
//!    hash chains (see `wots`, internal).
//! 2. **XMSS** -- An eXtended Merkle Signature Scheme that authenticates 2^h' WOTS+ keys
//!    via a binary Merkle tree, producing a few-time signature (see `xmss`, internal).
//! 3. **Hypertree** -- A tree of XMSS trees stacked in `d` layers, giving a many-time
//!    signature scheme with a total tree height of `h = d * h'` (see `hypertree`, internal).
//! 4. **FORS** -- A Forest of Random Subsets, a few-time signature used to sign the
//!    message digest before passing it to the hypertree (see `fors`, internal).
//! 5. **SLH-DSA** -- The top-level scheme that combines FORS + Hypertree to produce a
//!    stateless, many-time signature (see `slh`, internal).
//!
//! # Supported parameter sets
//!
//! This crate implements all six SHAKE-based parameter sets defined in FIPS 205 Section 11:
//!
//! | Type | 128-bit | 192-bit | 256-bit |
//! |------|---------|---------|---------|
//! | Small (s) | [`Shake128s`] | [`Shake192s`] | [`Shake256s`] |
//! | Fast (f)  | [`Shake128f`] | [`Shake192f`] | [`Shake256f`] |
//!
//! The "s" variants produce smaller signatures; the "f" variants are faster to sign and verify.
//!
//! # Examples
//!
//! ```rust
//! use quantica::slh_dsa::{SlhDsa, Shake128f, OsRng};
//!
//! // Generate a key pair
//! let mut rng = OsRng;
//! let (secret_key, public_key) = SlhDsa::<Shake128f>::keygen(&mut rng).unwrap();
//!
//! // Sign a message (empty context string)
//! let message = b"hello, post-quantum world!";
//! let signature = SlhDsa::<Shake128f>::sign(message, b"", &secret_key, &mut rng).unwrap();
//!
//! // Verify the signature
//! let valid = SlhDsa::<Shake128f>::verify(message, b"", &signature, &public_key).unwrap();
//! assert!(valid);
//! ```
//!
//! [FIPS 205]: https://doi.org/10.6028/NIST.FIPS.205

// API tiers: `params`/`rng` are facade; `address`/`hash`/`hash_sha2` are
// hazmat expert bricks (no stability promise); the signature components
// (WOTS+/XMSS/FORS/hypertree) are crate-internal — they are ONE-TIME /
// few-time primitives whose standalone misuse (key reuse) enables forgery.

/// Address structure used to domain-separate hash calls throughout SLH-DSA.
#[cfg(feature = "hazmat")]
pub mod address;
#[cfg(not(feature = "hazmat"))]
pub(crate) mod address;
// FORS few-time signature component — crate-internal (misuse hazard).
pub(crate) mod fors;
/// Tweakable hash functions (H_msg, PRF, PRF_msg, T_l, H, F) and the
/// SHAKE instantiation (FIPS 205 §11.1).
#[cfg(feature = "hazmat")]
pub mod hash;
#[cfg(not(feature = "hazmat"))]
pub(crate) mod hash;
/// SHA-2 instantiation of the tweakable hash functions (FIPS 205 §11.2).
#[cfg(feature = "hazmat")]
pub mod hash_sha2;
#[cfg(not(feature = "hazmat"))]
pub(crate) mod hash_sha2;
// Hypertree composition layer — crate-internal.
pub(crate) mod hypertree;
/// SLH-DSA parameter set definitions and the [`Params`] trait.
pub mod params;
/// Minimal cryptographic RNG trait and OS-backed implementation.
pub mod rng;
// SHAKE256 wrappers over the shared tessera core — crate-internal.
pub(crate) mod sha3;
/// Top-level SLH-DSA algorithms — the un-typed raw-slice facade (hazmat
/// tier: no typed-wrapper validation; used by the C FFI and KAT tooling).
#[cfg(feature = "hazmat")]
pub mod slh;
#[cfg(not(feature = "hazmat"))]
pub(crate) mod slh;
// WOTS+ ONE-TIME signature component — key reuse on two messages enables
// forgery; crate-internal.
pub(crate) mod wots;
// XMSS few-time component — crate-internal.
pub(crate) mod xmss;

// In-crate KATs for the `pub(crate)` internal interface (sign/verify_internal).
#[cfg(test)]
mod acvp_internal;

// Re-export parameter set types for convenience.
pub use crate::prehash::PreHash;
pub use params::{
    Params, Sha2_128f, Sha2_128s, Sha2_192f, Sha2_192s, Sha2_256f, Sha2_256s, Shake128f, Shake128s, Shake192f,
    Shake192s, Shake256f, Shake256s,
};
pub use rng::CryptoRng;
#[cfg(feature = "std")]
pub use rng::OsRng;

/// Errors that can occur in SLH-DSA operations.
///
/// These errors cover failures in random number generation, malformed keys or signatures,
/// and verification mismatches. All variants are non-recoverable in the sense that retrying
/// with the same inputs will produce the same error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SlhDsaError {
    /// The cryptographic random number generator failed to produce bytes.
    ///
    /// This typically indicates an OS-level failure (e.g., `/dev/urandom` unavailable).
    RngFailure,
    /// The provided key has an invalid format or unexpected length.
    ///
    /// Public keys must be `2*n` bytes and secret keys `4*n` bytes, where `n` is the
    /// security parameter ([`Params::N`]).
    InvalidKey,
    /// The provided signature has an invalid format or unexpected length.
    ///
    /// Signatures must be exactly [`SlhDsa::signature_size`] bytes for the chosen parameter set.
    InvalidSignature,
    /// The signature did not verify against the given message and public key.
    VerificationFailed,
    /// The context string exceeds the 255-byte maximum (FIPS 205 §10.2).
    ContextTooLong,
    /// Signing-side fault redundancy detected a mismatch between the two
    /// independent signing runs (item `T1-C` of the SLH-DSA SCA roadmap).
    ///
    /// Gated by the `sca-fors-redundancy` cargo feature, the signer
    /// produces the FORS signature twice and aborts before emission if
    /// the two results disagree — single-fault grafting-tree forgeries
    /// (Castelnovi 2018, Adiletta 2025) cannot then propagate out of
    /// the device. The error is non-recoverable; a retry on the same
    /// inputs will either succeed (the fault was transient) or surface
    /// the same error again.
    FaultDetected,
}

impl core::fmt::Display for SlhDsaError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            SlhDsaError::RngFailure => write!(f, "RNG failure"),
            SlhDsaError::InvalidKey => write!(f, "Invalid key"),
            SlhDsaError::InvalidSignature => write!(f, "Invalid signature"),
            SlhDsaError::VerificationFailed => write!(f, "Verification failed"),
            SlhDsaError::ContextTooLong => write!(f, "Context string exceeds 255 bytes"),
            SlhDsaError::FaultDetected => write!(f, "Signing-side fault detected by FORS redundancy"),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for SlhDsaError {}

use crate::secret::SecretBytes;
/// High-level SLH-DSA API parameterized by a parameter set.
///
/// This is the main entry point for using SLH-DSA. The type parameter `P` selects one of
/// the six SHAKE-based parameter sets (e.g., [`Shake128f`], [`Shake256s`]).
///
/// `SlhDsa` is a zero-sized type that serves as a namespace for the static methods
/// [`keygen`](Self::keygen), [`sign`](Self::sign), and [`verify`](Self::verify).
///
/// # Examples
///
/// ```rust
/// use quantica::slh_dsa::{SlhDsa, Shake256s, OsRng};
///
/// let mut rng = OsRng;
/// let (sk, pk) = SlhDsa::<Shake256s>::keygen(&mut rng).unwrap();
/// let sig = SlhDsa::<Shake256s>::sign(b"data", b"", &sk, &mut rng).unwrap();
/// assert!(SlhDsa::<Shake256s>::verify(b"data", b"", &sig, &pk).unwrap());
/// ```
use alloc::vec::Vec;
use core::marker::PhantomData;

// =====================================================================
// Typed key / signature wrappers
// =====================================================================

/// SLH-DSA **verifying key** (public key, `2 * P::N` bytes).
///
/// Type-tagged with `P`. No zeroization.
pub struct VerifyingKey<P: Params> {
    bytes: Vec<u8>,
    _marker: PhantomData<P>,
}

impl<P: Params> VerifyingKey<P> {
    /// Wrap a raw byte slice. Length is validated against
    /// [`Params::PK_LEN`].
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, SlhDsaError> {
        if bytes.len() != P::PK_LEN {
            return Err(SlhDsaError::InvalidKey);
        }
        Ok(Self {
            bytes: bytes.to_vec(),
            _marker: PhantomData,
        })
    }

    /// Borrow the encoded verifying key as a byte slice.
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Length in bytes (always [`Params::PK_LEN`]).
    pub fn len(&self) -> usize {
        self.bytes.len()
    }
}

impl<P: Params> AsRef<[u8]> for VerifyingKey<P> {
    fn as_ref(&self) -> &[u8] {
        &self.bytes
    }
}

impl<P: Params> core::ops::Deref for VerifyingKey<P> {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        &self.bytes
    }
}

impl<P: Params> Clone for VerifyingKey<P> {
    fn clone(&self) -> Self {
        Self {
            bytes: self.bytes.clone(),
            _marker: PhantomData,
        }
    }
}

/// SLH-DSA **signing key** (secret key, `4 * P::N` bytes).
///
/// Backed by [`SecretBytes`] — wipes its memory on [`Drop`] via
/// `silentops::ct_zeroize`. Type-tagged with `P`.
pub struct SigningKey<P: Params> {
    bytes: SecretBytes,
    _marker: PhantomData<P>,
}

impl<P: Params> SigningKey<P> {
    /// Wrap a raw byte slice. Length is validated against
    /// [`Params::SK_LEN`].
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, SlhDsaError> {
        if bytes.len() != P::SK_LEN {
            return Err(SlhDsaError::InvalidKey);
        }
        Ok(Self {
            bytes: SecretBytes::from_slice(bytes),
            _marker: PhantomData,
        })
    }

    /// Borrow the encoded signing key as a byte slice.
    pub fn as_bytes(&self) -> &[u8] {
        self.bytes.as_bytes()
    }

    /// Length in bytes (always [`Params::SK_LEN`]).
    pub fn len(&self) -> usize {
        self.bytes.len()
    }
}

impl<P: Params> AsRef<[u8]> for SigningKey<P> {
    fn as_ref(&self) -> &[u8] {
        self.bytes.as_bytes()
    }
}

impl<P: Params> core::ops::Deref for SigningKey<P> {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        self.bytes.as_bytes()
    }
}

/// SLH-DSA **signature**. Type-tagged with `P`.
///
/// Public material — not zeroized.
pub struct Signature<P: Params> {
    bytes: Vec<u8>,
    _marker: PhantomData<P>,
}

impl<P: Params> Signature<P> {
    /// Wrap a raw byte slice. Length is validated against
    /// [`params::sig_len::<P>()`].
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, SlhDsaError> {
        if bytes.len() != params::sig_len::<P>() {
            return Err(SlhDsaError::InvalidSignature);
        }
        Ok(Self {
            bytes: bytes.to_vec(),
            _marker: PhantomData,
        })
    }

    /// Borrow the encoded signature as a byte slice.
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Length in bytes (always [`params::sig_len::<P>()`]).
    pub fn len(&self) -> usize {
        self.bytes.len()
    }
}

impl<P: Params> AsRef<[u8]> for Signature<P> {
    fn as_ref(&self) -> &[u8] {
        &self.bytes
    }
}

impl<P: Params> core::ops::Deref for Signature<P> {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        &self.bytes
    }
}

impl<P: Params> Clone for Signature<P> {
    fn clone(&self) -> Self {
        Self {
            bytes: self.bytes.clone(),
            _marker: PhantomData,
        }
    }
}

/// Generic SLH-DSA interface parameterized by parameter set (FIPS 205).
///
/// This struct provides the high-level API for SLH-DSA key generation,
/// signing, and verification. The type parameter `P` selects one of the
/// twelve FIPS 205 parameter sets (`Sha2_128s` … `Shake256f`) defined in
/// the `params` module.
///
/// All methods are stateless; `SlhDsa` carries no runtime data and exists
/// only to bind the parameter set at the type level.
pub struct SlhDsa<P: Params> {
    _marker: core::marker::PhantomData<P>,
}

impl<P: Params> SlhDsa<P> {
    /// Generate a new SLH-DSA key pair using the provided RNG.
    ///
    /// Implements Algorithm 21 of FIPS 205.
    ///
    /// # Arguments
    ///
    /// * `rng` - A cryptographic random number generator implementing [`CryptoRng`].
    ///
    /// # Returns
    ///
    /// A tuple `(secret_key, public_key)` of typed wrappers. The secret key is
    /// `4*n` bytes and the public key is `2*n` bytes, where `n = P::N`.
    ///
    /// # Errors
    ///
    /// * [`SlhDsaError::RngFailure`] if the RNG cannot provide bytes.
    pub fn keygen(rng: &mut dyn CryptoRng) -> Result<(SigningKey<P>, VerifyingKey<P>), SlhDsaError> {
        let (sk_v, pk_v) = slh::slh_keygen::<P>(rng)?;
        Ok((
            SigningKey {
                bytes: SecretBytes::from_vec(sk_v),
                _marker: PhantomData,
            },
            VerifyingKey {
                bytes: pk_v,
                _marker: PhantomData,
            },
        ))
    }

    /// Sign a message with an optional context string (hedged mode).
    ///
    /// Implements Algorithm 22 of FIPS 205 (external SLH-DSA.Sign): wraps
    /// the message as `M' = 0x00 || len(ctx) || ctx || message` for domain
    /// separation, then hedged-signs it. Use an empty `ctx` (`b""`) when no
    /// context is needed — the wrapping still applies, keeping signatures
    /// interoperable with conformant verifiers.
    ///
    /// # Arguments
    ///
    /// * `message` - The message to sign (arbitrary length).
    /// * `ctx` - Optional context string, at most 255 bytes (`b""` for none).
    /// * `secret_key` - The signing key for this parameter set.
    /// * `rng` - A cryptographic random number generator implementing [`CryptoRng`].
    ///
    /// # Returns
    ///
    /// A [`Signature<P>`] of length [`SlhDsa::signature_size`].
    ///
    /// # Errors
    ///
    /// * [`SlhDsaError::ContextTooLong`] if `ctx` exceeds 255 bytes.
    /// * [`SlhDsaError::RngFailure`] if the RNG cannot provide bytes.
    /// * [`SlhDsaError::FaultDetected`] if the `sca-fors-redundancy` feature is
    ///   enabled and the two independent signing runs disagree.
    pub fn sign(
        message: &[u8],
        ctx: &[u8],
        secret_key: &SigningKey<P>,
        rng: &mut dyn CryptoRng,
    ) -> Result<Signature<P>, SlhDsaError> {
        let sig_v = slh::slh_sign::<P>(message, ctx, secret_key.as_bytes(), rng)?;
        Ok(Signature {
            bytes: sig_v,
            _marker: PhantomData,
        })
    }

    /// Sign with pre-hashing — HashSLH-DSA (Algorithm 23 of FIPS 205).
    ///
    /// The message is replaced by its digest under `ph`; the library
    /// computes `ph(message)` and embeds the matching OID, forming
    /// `M' = 0x01 || len(ctx) || ctx || OID(ph) || ph(message)`.
    ///
    /// # Arguments
    ///
    /// * `message` - The message to pre-hash and sign (arbitrary length).
    /// * `ctx` - Optional context string, at most 255 bytes (`b""` for none).
    /// * `ph` - The pre-hash function [`PreHash`] applied to `message`.
    /// * `secret_key` - The signing key for this parameter set.
    /// * `rng` - A cryptographic random number generator implementing [`CryptoRng`].
    ///
    /// # Returns
    ///
    /// A [`Signature<P>`] of length [`SlhDsa::signature_size`].
    ///
    /// # Errors
    ///
    /// * [`SlhDsaError::ContextTooLong`] if `ctx` exceeds 255 bytes.
    /// * [`SlhDsaError::RngFailure`] if the RNG cannot provide bytes.
    /// * [`SlhDsaError::FaultDetected`] if the `sca-fors-redundancy` feature is
    ///   enabled and the two independent signing runs disagree.
    pub fn sign_prehash(
        message: &[u8],
        ctx: &[u8],
        ph: PreHash,
        secret_key: &SigningKey<P>,
        rng: &mut dyn CryptoRng,
    ) -> Result<Signature<P>, SlhDsaError> {
        let sig_v = slh::slh_sign_prehash::<P>(message, ctx, ph, secret_key.as_bytes(), rng)?;
        Ok(Signature {
            bytes: sig_v,
            _marker: PhantomData,
        })
    }

    /// Verify a signature on a message with an optional context string.
    ///
    /// Implements Algorithm 24 of FIPS 205 (external SLH-DSA.Verify):
    /// reconstructs `M' = 0x00 || len(ctx) || ctx || message` and checks it.
    /// `ctx` must match the one used at signing time.
    ///
    /// # Arguments
    ///
    /// * `message` - The signed message.
    /// * `ctx` - The context string used during signing, at most 255 bytes.
    /// * `signature` - The signature to check.
    /// * `public_key` - The verifying key for this parameter set.
    ///
    /// # Returns
    ///
    /// `Ok(true)` if the signature is valid, `Ok(false)` if it does not verify.
    ///
    /// # Errors
    ///
    /// * [`SlhDsaError::ContextTooLong`] if `ctx` exceeds 255 bytes.
    /// * [`SlhDsaError::InvalidKey`] if `public_key` has the wrong length.
    /// * [`SlhDsaError::InvalidSignature`] if `signature` has the wrong length.
    pub fn verify(
        message: &[u8],
        ctx: &[u8],
        signature: &Signature<P>,
        public_key: &VerifyingKey<P>,
    ) -> Result<bool, SlhDsaError> {
        slh::slh_verify::<P>(message, signature.as_bytes(), ctx, public_key.as_bytes())
    }

    /// Verify a pre-hash HashSLH-DSA signature (Algorithm 25 of FIPS 205).
    ///
    /// `ph` must match the [`PreHash`] used at signing time.
    ///
    /// # Arguments
    ///
    /// * `message` - The signed message.
    /// * `ctx` - The context string used during signing, at most 255 bytes.
    /// * `ph` - The pre-hash function [`PreHash`], matching the one used at signing.
    /// * `signature` - The signature to check.
    /// * `public_key` - The verifying key for this parameter set.
    ///
    /// # Returns
    ///
    /// `Ok(true)` if the signature is valid, `Ok(false)` if it does not verify.
    ///
    /// # Errors
    ///
    /// * [`SlhDsaError::ContextTooLong`] if `ctx` exceeds 255 bytes.
    /// * [`SlhDsaError::InvalidKey`] if `public_key` has the wrong length.
    /// * [`SlhDsaError::InvalidSignature`] if `signature` has the wrong length.
    pub fn verify_prehash(
        message: &[u8],
        ctx: &[u8],
        ph: PreHash,
        signature: &Signature<P>,
        public_key: &VerifyingKey<P>,
    ) -> Result<bool, SlhDsaError> {
        slh::slh_verify_prehash::<P>(message, signature.as_bytes(), ctx, ph, public_key.as_bytes())
    }

    /// Returns the expected signature size in bytes for this parameter set.
    ///
    /// The signature consists of a randomizer `R` (n bytes), a FORS signature, and a
    /// hypertree signature: `n + k*(1+a)*n + (h + d*len)*n`.
    pub fn signature_size() -> usize {
        params::sig_len::<P>()
    }

    /// Returns the expected public key size in bytes (`2*n`).
    pub fn public_key_size() -> usize {
        P::PK_LEN
    }

    /// Returns the expected secret key size in bytes (`4*n`).
    pub fn secret_key_size() -> usize {
        P::SK_LEN
    }
}