krypteia-quantica 0.1.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
//! 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`]).
//! 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`]).
//! 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`]).
//! 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`]).
//! 5. **SLH-DSA** -- The top-level scheme that combines FORS + Hypertree to produce a
//!    stateless, many-time signature (see [`slh`]).
//!
//! # 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
//! let message = b"hello, post-quantum world!";
//! let signature = SlhDsa::<Shake128f>::sign(message, &secret_key, &mut rng).unwrap();
//!
//! // Verify the signature
//! let valid = SlhDsa::<Shake128f>::verify(message, &signature, &public_key).unwrap();
//! assert!(valid);
//! ```
//!
//! [FIPS 205]: https://doi.org/10.6028/NIST.FIPS.205

/// Address structure used to domain-separate hash calls throughout SLH-DSA.
pub mod address;
/// FORS: Forest of Random Subsets few-time signature scheme.
pub mod fors;
/// SHAKE-based tweakable hash function wrappers (H_msg, PRF, PRF_msg, T_l, H, F).
pub mod hash;
/// Hypertree: a d-layer tree of XMSS trees for many-time signing.
pub 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;
/// `Keccak-f[1600]` based SHAKE256 implementation (FIPS 202).
pub mod sha3;
/// Top-level SLH-DSA key generation, signing, and verification algorithms.
pub mod slh;
/// WOTS+ one-time signature scheme based on hash chains.
pub mod wots;
/// XMSS: eXtended Merkle Signature Scheme combining WOTS+ with a Merkle tree.
pub mod xmss;

// Re-export parameter set types for convenience.
pub use params::{Params, 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,
    /// 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::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", &sk, &mut rng).unwrap();
/// assert!(SlhDsa::<Shake256s>::verify(b"data", &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,
        }
    }
}

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.
    ///
    /// Returns `(secret_key, public_key)` as byte vectors. The secret key is `4*n` bytes
    /// and the public key is `2*n` bytes, where `n = P::N`.
    ///
    /// Implements Algorithm 21 of FIPS 205.
    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,
            },
        ))
    }

    /// Generate a key pair deterministically from explicit seed material.
    ///
    /// This is the internal/deterministic variant (Algorithm 18 of FIPS 205). Each of
    /// `sk_seed`, `sk_prf`, and `pk_seed` must be exactly `P::N` bytes.
    ///
    /// Returns `(secret_key, public_key)`.
    pub fn keygen_internal(sk_seed: &[u8], sk_prf: &[u8], pk_seed: &[u8]) -> (Vec<u8>, Vec<u8>) {
        slh::slh_keygen_internal::<P>(sk_seed, sk_prf, pk_seed)
    }

    /// Sign a message using randomized (hedged) signing.
    ///
    /// Produces a signature over `message` using the given `secret_key` and fresh randomness
    /// from `rng`. The randomness provides hedged signing: even if the RNG is weak, security
    /// degrades gracefully.
    ///
    /// Implements Algorithm 22 of FIPS 205.
    pub fn sign(
        message: &[u8],
        secret_key: &SigningKey<P>,
        rng: &mut dyn CryptoRng,
    ) -> Result<Signature<P>, SlhDsaError> {
        let sig_v = slh::slh_sign::<P>(message, secret_key.as_bytes(), rng)?;
        Ok(Signature {
            bytes: sig_v,
            _marker: PhantomData,
        })
    }

    /// Sign a message with explicit additional randomness (internal variant).
    ///
    /// This is Algorithm 19 of FIPS 205. The `addrnd` parameter is `P::N` bytes of
    /// optional randomness; passing `pk_seed` here yields deterministic signing.
    ///
    /// Without the `sca-fors-redundancy` feature this is always [`Ok`]. With it,
    /// the T1-C FORS recompute-and-compare check can return
    /// [`Err(SlhDsaError::FaultDetected)`][SlhDsaError].
    pub fn sign_internal(message: &[u8], secret_key: &[u8], addrnd: &[u8]) -> Result<Vec<u8>, SlhDsaError> {
        slh::slh_sign_internal::<P>(message, secret_key, addrnd)
    }

    /// Verify a signature on a message against a public key.
    ///
    /// Returns `Ok(true)` if the signature is valid, `Ok(false)` if the signature is
    /// well-formed but does not verify, or an `Err` if the key or signature has an
    /// invalid length.
    ///
    /// Implements Algorithm 24 of FIPS 205.
    pub fn verify(message: &[u8], signature: &Signature<P>, public_key: &VerifyingKey<P>) -> Result<bool, SlhDsaError> {
        slh::slh_verify::<P>(message, signature.as_bytes(), 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
    }
}