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
// 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)]

//! ML-DSA: Module-Lattice-Based Digital Signature Standard (FIPS 204).
//!
//! This crate implements the ML-DSA (formerly CRYSTALS-Dilithium) digital signature
//! scheme as specified in FIPS 204. ML-DSA is a post-quantum lattice-based signature
//! scheme built on the hardness of the Module Learning With Errors (M-LWE) and
//! Module Short Integer Solution (M-SIS) problems.
//!
//! Three parameter sets are provided, corresponding to NIST security levels 2, 3, and 5:
//!
//! - [`MlDsa44Scheme`] -- ML-DSA-44 (security level 2, ~128-bit classical security)
//! - [`MlDsa65Scheme`] -- ML-DSA-65 (security level 3, ~192-bit classical security)
//! - [`MlDsa87Scheme`] -- ML-DSA-87 (security level 5, ~256-bit classical security)
//!
//! # Examples
//!
//! ```rust
//! use quantica::ml_dsa::{MlDsa44Scheme, OsRng, MlDsa};
//!
//! let mut rng = OsRng;
//! let (pk, sk) = MlDsa44Scheme::keygen(&mut rng).unwrap();
//! let msg = b"Hello, post-quantum world!";
//! let sig = MlDsa44Scheme::sign(&sk, msg, b"", &mut rng).unwrap();
//! let valid = MlDsa44Scheme::verify(&pk, msg, b"", &sig).unwrap();
//! assert!(valid);
//! ```

// API tiers: `params`/`rng` are facade; `decompose`/`encode`/`sample` are
// hazmat expert bricks (no stability promise); everything else is internal.

/// Decomposition, rounding, and hint functions for signatures.
#[cfg(feature = "hazmat")]
pub mod decompose;
#[cfg(not(feature = "hazmat"))]
pub(crate) mod decompose;
/// Core ML-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 dsa;
#[cfg(not(feature = "hazmat"))]
pub(crate) mod dsa;
/// Encoding and decoding of keys, signatures, and polynomials.
#[cfg(feature = "hazmat")]
pub mod encode;
#[cfg(not(feature = "hazmat"))]
pub(crate) mod encode;
// NTT — Montgomery domain with lazy reduction; crate-internal (naive
// standalone use is incorrect).
pub(crate) mod ntt;
/// ML-DSA parameter sets and constants (FIPS 204, Table 1).
pub mod params;
/// Cryptographic random number generation trait and OS-backed implementation.
pub mod rng;
/// Sampling algorithms for matrix, secret, and masking generation.
#[cfg(feature = "hazmat")]
pub mod sample;
#[cfg(not(feature = "hazmat"))]
pub(crate) mod sample;
// Keccak/SHA-3/SHAKE wrappers over the shared tessera core.
pub(crate) mod sha3;

// First-order arithmetic masking (DPA / template countermeasure) — SCA
// work-in-progress per the Tier roadmap; crate-internal.
#[cfg(feature = "sca-protected")]
pub(crate) mod masked;

// Fisher-Yates shuffled NTT (SPA countermeasure) — SCA WIP; crate-internal.
#[cfg(feature = "sca-protected")]
pub(crate) mod shuffle;

// Small polynomial representation (i16) for secret vectors — RAM
// optimization WIP with a strict correctness precondition; crate-internal.
#[cfg(feature = "small-secret")]
pub(crate) mod smallpoly;

// Compressed polynomial / challenge storage — RAM layout WIP; crate-internal.
#[cfg(any(feature = "compressed-poly", feature = "compressed-challenge"))]
pub(crate) mod compressed;

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

use alloc::vec::Vec;
use core::marker::PhantomData;

pub use crate::prehash::PreHash;
pub use params::{MlDsa44, MlDsa65, MlDsa87, Params};
pub use rng::CryptoRng;
#[cfg(feature = "std")]
pub use rng::OsRng;

use crate::secret::SecretBytes;

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

/// ML-DSA **verifying key** (the public half of a key pair).
///
/// Type-tagged with the parameter set `P`. Public material — no
/// zeroization is performed on drop.
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, MlDsaError> {
        if bytes.len() != P::PK_LEN {
            return Err(MlDsaError::InvalidPublicKey);
        }
        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,
        }
    }
}

/// ML-DSA **signing key** (the private half of a key pair).
///
/// Backed by [`SecretBytes`] — wipes its memory on [`Drop`] via
/// `silentops::ct_zeroize`. Type-tagged with `P` to prevent
/// cross-parameter-set use.
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, MlDsaError> {
        if bytes.len() != P::SK_LEN {
            return Err(MlDsaError::InvalidSecretKey);
        }
        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()
    }
}

/// ML-DSA **signature**. Type-tagged with the parameter set `P`.
///
/// Signatures are public material (transmitted alongside the message)
/// and are 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`].
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, MlDsaError> {
        if bytes.len() != P::SIG_LEN {
            return Err(MlDsaError::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`]).
    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,
        }
    }
}

/// Error types for ML-DSA operations.
///
/// Each variant corresponds to a specific failure mode that can occur during
/// key generation, signing, or verification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MlDsaError {
    /// Random number generation failed.
    ///
    /// Returned when the underlying RNG (e.g., `/dev/urandom`) cannot provide bytes.
    RngFailure,
    /// Invalid public key (wrong length or format).
    ///
    /// The provided public key does not have the expected byte length for the
    /// chosen parameter set.
    InvalidPublicKey,
    /// Invalid secret key (wrong length or format).
    ///
    /// The provided secret key does not have the expected byte length for the
    /// chosen parameter set.
    InvalidSecretKey,
    /// Invalid signature (wrong length or format).
    ///
    /// The provided signature does not have the expected byte length for the
    /// chosen parameter set, or its internal encoding is malformed.
    InvalidSignature,
    /// Context string too long (> 255 bytes).
    ///
    /// FIPS 204 limits the optional context string to at most 255 bytes.
    ContextTooLong,
    /// Signature verification failed.
    VerificationFailed,
}

impl core::fmt::Display for MlDsaError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            MlDsaError::RngFailure => write!(f, "RNG failure"),
            MlDsaError::InvalidPublicKey => write!(f, "Invalid public key"),
            MlDsaError::InvalidSecretKey => write!(f, "Invalid secret key"),
            MlDsaError::InvalidSignature => write!(f, "Invalid signature"),
            MlDsaError::ContextTooLong => write!(f, "Context string too long"),
            MlDsaError::VerificationFailed => write!(f, "Signature verification failed"),
        }
    }
}

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

/// Generic ML-DSA interface parameterized by security level.
///
/// This struct provides the high-level API for ML-DSA key generation, signing,
/// and verification. The type parameter `P` selects the parameter set
/// ([`MlDsa44`], [`MlDsa65`], or [`MlDsa87`]).
///
/// All methods are stateless; [`MlDsa`] carries no runtime data and exists only
/// to bind the parameter set at the type level.
pub struct MlDsa<P: Params> {
    _marker: PhantomData<P>,
}

impl<P: Params> MlDsa<P> {
    /// Generate a new ML-DSA key pair.
    ///
    /// Implements Algorithm 1 of FIPS 204 (ML-DSA.KeyGen). Draws 32 random
    /// bytes from `rng` and derives a public key / secret key pair.
    ///
    /// Returns `(pk, sk)` where `pk` has length [`Self::PK_LEN`] and `sk` has
    /// length [`Self::SK_LEN`].
    ///
    /// # Errors
    ///
    /// Returns [`MlDsaError::RngFailure`] if the RNG cannot provide bytes.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use quantica::ml_dsa::{MlDsa, MlDsa44, OsRng};
    ///
    /// let mut rng = OsRng;
    /// let (pk, sk) = MlDsa::<MlDsa44>::keygen(&mut rng).unwrap();
    /// assert_eq!(pk.len(), MlDsa::<MlDsa44>::PK_LEN);
    /// assert_eq!(sk.len(), MlDsa::<MlDsa44>::SK_LEN);
    /// ```
    pub fn keygen(rng: &mut dyn CryptoRng) -> Result<(VerifyingKey<P>, SigningKey<P>), MlDsaError> {
        let (pk_v, sk_v) = dsa::keygen::<P>(rng)?;
        Ok((
            VerifyingKey {
                bytes: pk_v,
                _marker: PhantomData,
            },
            SigningKey {
                bytes: SecretBytes::from_vec(sk_v),
                _marker: PhantomData,
            },
        ))
    }

    /// Sign a message with an optional context string.
    ///
    /// Implements Algorithm 2 of FIPS 204 (ML-DSA.Sign). Uses **hedged signing**:
    /// 32 random bytes are drawn from `rng` and mixed with the secret key material
    /// to produce the per-signature nonce. This provides resilience against
    /// fault attacks compared to purely deterministic signing.
    ///
    /// The signing algorithm uses a rejection sampling loop internally: candidate
    /// signatures are generated until one passes all norm checks, so execution
    /// time may vary.
    ///
    /// - `sk`: secret key (must be [`Self::SK_LEN`] bytes).
    /// - `msg`: message to sign (arbitrary length).
    /// - `ctx`: optional context string (at most 255 bytes).
    /// - `rng`: source of randomness for hedged signing.
    ///
    /// Returns a signature of length [`Self::SIG_LEN`].
    ///
    /// # Errors
    ///
    /// - [`MlDsaError::InvalidSecretKey`] if `sk` has the wrong length.
    /// - [`MlDsaError::ContextTooLong`] if `ctx` exceeds 255 bytes.
    /// - [`MlDsaError::RngFailure`] if the RNG cannot provide bytes.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use quantica::ml_dsa::{MlDsa, MlDsa44, OsRng};
    ///
    /// let mut rng = OsRng;
    /// let (pk, sk) = MlDsa::<MlDsa44>::keygen(&mut rng).unwrap();
    /// let sig = MlDsa::<MlDsa44>::sign(&sk, b"message", b"", &mut rng).unwrap();
    /// assert_eq!(sig.len(), MlDsa::<MlDsa44>::SIG_LEN);
    /// ```
    pub fn sign(
        sk: &SigningKey<P>,
        msg: &[u8],
        ctx: &[u8],
        rng: &mut dyn CryptoRng,
    ) -> Result<Signature<P>, MlDsaError> {
        let sig_v = dsa::sign::<P>(sk.as_bytes(), msg, ctx, rng)?;
        Ok(Signature {
            bytes: sig_v,
            _marker: PhantomData,
        })
    }

    /// Sign with pre-hashing — HashML-DSA (Algorithm 4 of FIPS 204).
    ///
    /// The message is replaced by its digest under `ph` (e.g.
    /// [`PreHash::Sha256`]); the library computes `ph(msg)` and embeds the
    /// matching OID, producing `M' = 0x01 || len(ctx) || ctx || OID || ph(msg)`.
    ///
    /// # Arguments
    ///
    /// * `sk` - The secret key (must be [`Self::SK_LEN`] bytes).
    /// * `msg` - 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 `msg`.
    /// * `rng` - Source of randomness for hedged signing.
    ///
    /// # Returns
    ///
    /// A [`Signature<P>`] of length [`Self::SIG_LEN`].
    ///
    /// # Errors
    ///
    /// * [`MlDsaError::InvalidSecretKey`] if `sk` has the wrong length.
    /// * [`MlDsaError::ContextTooLong`] if `ctx` exceeds 255 bytes.
    /// * [`MlDsaError::RngFailure`] if the RNG cannot provide bytes.
    pub fn sign_prehash(
        sk: &SigningKey<P>,
        msg: &[u8],
        ctx: &[u8],
        ph: PreHash,
        rng: &mut dyn CryptoRng,
    ) -> Result<Signature<P>, MlDsaError> {
        let sig_v = dsa::sign_prehash::<P>(sk.as_bytes(), msg, ctx, ph, rng)?;
        Ok(Signature {
            bytes: sig_v,
            _marker: PhantomData,
        })
    }

    /// Verify a signature on a message with an optional context string.
    ///
    /// Implements Algorithm 3 of FIPS 204 (ML-DSA.Verify).
    ///
    /// - `pk`: public key (must be [`Self::PK_LEN`] bytes).
    /// - `msg`: the signed message.
    /// - `ctx`: the context string used during signing (at most 255 bytes).
    /// - `sig`: the signature (must be [`Self::SIG_LEN`] bytes).
    ///
    /// Returns `Ok(true)` if the signature is valid, `Ok(false)` if verification
    /// fails (invalid signature content), or an `Err` for structural issues.
    ///
    /// # Errors
    ///
    /// - [`MlDsaError::InvalidPublicKey`] if `pk` has the wrong length.
    /// - [`MlDsaError::InvalidSignature`] if `sig` has the wrong length.
    /// - [`MlDsaError::ContextTooLong`] if `ctx` exceeds 255 bytes.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use quantica::ml_dsa::{MlDsa, MlDsa44, OsRng};
    ///
    /// let mut rng = OsRng;
    /// let (pk, sk) = MlDsa::<MlDsa44>::keygen(&mut rng).unwrap();
    /// let sig = MlDsa::<MlDsa44>::sign(&sk, b"msg", b"", &mut rng).unwrap();
    /// assert!(MlDsa::<MlDsa44>::verify(&pk, b"msg", b"", &sig).unwrap());
    /// ```
    pub fn verify(pk: &VerifyingKey<P>, msg: &[u8], ctx: &[u8], sig: &Signature<P>) -> Result<bool, MlDsaError> {
        dsa::verify::<P>(pk.as_bytes(), msg, ctx, sig.as_bytes())
    }

    /// Verify a pre-hash HashML-DSA signature (Algorithm 5 of FIPS 204).
    ///
    /// `ph` must match the [`PreHash`] used at signing time.
    ///
    /// # Arguments
    ///
    /// * `pk` - The public key (must be [`Self::PK_LEN`] bytes).
    /// * `msg` - 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.
    /// * `sig` - The signature (must be [`Self::SIG_LEN`] bytes).
    ///
    /// # Returns
    ///
    /// `Ok(true)` if the signature is valid, `Ok(false)` if verification fails.
    ///
    /// # Errors
    ///
    /// * [`MlDsaError::InvalidPublicKey`] if `pk` has the wrong length.
    /// * [`MlDsaError::InvalidSignature`] if `sig` has the wrong length.
    /// * [`MlDsaError::ContextTooLong`] if `ctx` exceeds 255 bytes.
    pub fn verify_prehash(
        pk: &VerifyingKey<P>,
        msg: &[u8],
        ctx: &[u8],
        ph: PreHash,
        sig: &Signature<P>,
    ) -> Result<bool, MlDsaError> {
        dsa::verify_prehash::<P>(pk.as_bytes(), msg, ctx, ph, sig.as_bytes())
    }

    /// Public key length in bytes for this parameter set.
    pub const PK_LEN: usize = P::PK_LEN;

    /// Secret key length in bytes for this parameter set.
    pub const SK_LEN: usize = P::SK_LEN;

    /// Signature length in bytes for this parameter set.
    pub const SIG_LEN: usize = P::SIG_LEN;
}

/// Convenience alias for ML-DSA-44 (NIST security level 2).
pub type MlDsa44Scheme = MlDsa<MlDsa44>;
/// Convenience alias for ML-DSA-65 (NIST security level 3).
pub type MlDsa65Scheme = MlDsa<MlDsa65>;
/// Convenience alias for ML-DSA-87 (NIST security level 5).
pub type MlDsa87Scheme = MlDsa<MlDsa87>;