lib-q-cb-kem 0.0.4

Classical McEliece KEM implementation for lib-Q post-quantum cryptography library
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! lib-Q Classical McEliece Provider Implementation
//!
//! This module provides the LibQCbKemProvider that implements the KemOperations
//! trait and routes Classical McEliece KEM operations to the appropriate algorithm
//! implementations with proper security validation.

#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "alloc")]
use alloc::{
    string::ToString,
    vec::Vec,
};

#[cfg(feature = "alloc")]
use lib_q_core::api::{
    Algorithm,
    CryptoProvider,
    KemOperations,
};
#[cfg(feature = "alloc")]
use lib_q_core::error::{
    Error,
    Result,
};
#[cfg(feature = "alloc")]
use lib_q_core::security::SecurityValidator;
#[cfg(feature = "alloc")]
use lib_q_core::traits::{
    KemKeypair,
    KemPublicKey,
    KemSecretKey,
};

// Import Classical McEliece implementations
#[cfg(feature = "alloc")]
use crate::{
    CRYPTO_BYTES,
    CRYPTO_CIPHERTEXTBYTES,
    CRYPTO_PUBLICKEYBYTES,
    CRYPTO_SECRETKEYBYTES,
    Ciphertext,
    PublicKey,
    SecretKey,
    decapsulate,
    encapsulate,
    keypair,
};

/// lib-Q Classical McEliece KEM provider implementation
///
/// This provider implements KEM operations for Classical McEliece, including key generation,
/// encapsulation, and decapsulation with proper security validation and algorithm routing.
#[cfg(feature = "alloc")]
#[derive(Clone)]
pub struct LibQCbKemProvider {
    security_validator: SecurityValidator,
}

#[cfg(feature = "alloc")]
impl core::fmt::Debug for LibQCbKemProvider {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("LibQCbKemProvider")
            .field("security_validator", &"<SecurityValidator>")
            .finish()
    }
}

#[cfg(feature = "alloc")]
impl LibQCbKemProvider {
    /// Create a new Classical McEliece KEM provider
    ///
    /// # Returns
    ///
    /// A new instance of LibQCbKemProvider with security validation initialized.
    ///
    /// # Errors
    ///
    /// Returns an error if the security validator fails to initialize.
    pub fn new() -> Result<Self> {
        Ok(Self {
            security_validator: SecurityValidator::new()?,
        })
    }

    /// Get the security validator
    pub fn security_validator(&self) -> &SecurityValidator {
        &self.security_validator
    }

    /// Get mutable access to the security validator
    ///
    /// This method is provided for testing scenarios where entropy validation
    /// needs to be disabled for deterministic testing. Use with caution in production.
    pub fn security_validator_mut(&mut self) -> &mut SecurityValidator {
        &mut self.security_validator
    }
}

#[cfg(feature = "alloc")]
impl KemOperations for LibQCbKemProvider {
    fn generate_keypair(
        &self,
        algorithm: Algorithm,
        randomness: Option<&[u8]>,
    ) -> Result<KemKeypair> {
        // Validate algorithm category
        self.security_validator
            .validate_algorithm_category(algorithm, lib_q_core::api::AlgorithmCategory::Kem)?;

        // Validate randomness if provided
        if let Some(rng) = randomness {
            self.security_validator.validate_randomness(rng)?;
        }

        // Route to specific algorithm implementation
        match algorithm {
            // Classical McEliece algorithms
            Algorithm::CbKem348864 => self.generate_cb_kem_keypair(
                CRYPTO_PUBLICKEYBYTES,
                CRYPTO_SECRETKEYBYTES,
                randomness,
            ),
            Algorithm::CbKem460896 => self.generate_cb_kem_keypair(
                CRYPTO_PUBLICKEYBYTES,
                CRYPTO_SECRETKEYBYTES,
                randomness,
            ),
            Algorithm::CbKem6688128 => self.generate_cb_kem_keypair(
                CRYPTO_PUBLICKEYBYTES,
                CRYPTO_SECRETKEYBYTES,
                randomness,
            ),
            Algorithm::CbKem6960119 => self.generate_cb_kem_keypair(
                CRYPTO_PUBLICKEYBYTES,
                CRYPTO_SECRETKEYBYTES,
                randomness,
            ),
            Algorithm::CbKem8192128 => self.generate_cb_kem_keypair(
                CRYPTO_PUBLICKEYBYTES,
                CRYPTO_SECRETKEYBYTES,
                randomness,
            ),

            _ => Err(Error::InvalidAlgorithm {
                algorithm: "Algorithm not supported for Classical McEliece KEM operations",
            }),
        }
    }

    fn encapsulate(
        &self,
        algorithm: Algorithm,
        public_key: &KemPublicKey,
        randomness: Option<&[u8]>,
    ) -> Result<(Vec<u8>, Vec<u8>)> {
        // Validate algorithm category
        self.security_validator
            .validate_algorithm_category(algorithm, lib_q_core::api::AlgorithmCategory::Kem)?;

        // Validate public key size only (skip entropy validation for CB-KEM keys)
        self.security_validator
            .validate_key_size(algorithm, public_key.as_bytes(), false)?;

        // Validate randomness if provided
        if let Some(rng) = randomness {
            self.security_validator.validate_randomness(rng)?;
        }

        // Route to specific algorithm implementation
        match algorithm {
            // Classical McEliece algorithms
            Algorithm::CbKem348864 |
            Algorithm::CbKem460896 |
            Algorithm::CbKem6688128 |
            Algorithm::CbKem6960119 |
            Algorithm::CbKem8192128 => self.encapsulate_cb_kem(public_key, randomness),

            _ => Err(Error::InvalidAlgorithm {
                algorithm: "Algorithm not supported for Classical McEliece KEM operations",
            }),
        }
    }

    fn decapsulate(
        &self,
        algorithm: Algorithm,
        secret_key: &KemSecretKey,
        ciphertext: &[u8],
    ) -> Result<Vec<u8>> {
        // Validate algorithm category
        self.security_validator
            .validate_algorithm_category(algorithm, lib_q_core::api::AlgorithmCategory::Kem)?;

        // Validate secret key size only (skip entropy validation for CB-KEM keys)
        self.security_validator
            .validate_key_size(algorithm, secret_key.as_bytes(), true)?;

        // Validate ciphertext
        self.security_validator
            .validate_ciphertext(algorithm, ciphertext)?;

        // Route to specific algorithm implementation
        match algorithm {
            // Classical McEliece algorithms
            Algorithm::CbKem348864 |
            Algorithm::CbKem460896 |
            Algorithm::CbKem6688128 |
            Algorithm::CbKem6960119 |
            Algorithm::CbKem8192128 => self.decapsulate_cb_kem(secret_key, ciphertext),

            _ => Err(Error::InvalidAlgorithm {
                algorithm: "Algorithm not supported for Classical McEliece KEM operations",
            }),
        }
    }

    fn derive_public_key(
        &self,
        _algorithm: Algorithm,
        _secret_key: &KemSecretKey,
    ) -> Result<KemPublicKey> {
        // Classical McEliece doesn't support public key derivation from secret key
        // The public key is generated independently during keypair generation
        Err(Error::UnsupportedOperation {
            operation: "Classical McEliece does not support public key derivation from secret key"
                .to_string(),
        })
    }
}

#[cfg(feature = "alloc")]
impl LibQCbKemProvider {
    /// Generate a Classical McEliece keypair
    fn generate_cb_kem_keypair(
        &self,
        public_key_size: usize,
        secret_key_size: usize,
        randomness: Option<&[u8]>,
    ) -> Result<KemKeypair> {
        // Validate key sizes
        if public_key_size != CRYPTO_PUBLICKEYBYTES {
            return Err(Error::InvalidKeySize {
                expected: CRYPTO_PUBLICKEYBYTES,
                actual: public_key_size,
            });
        }
        if secret_key_size != CRYPTO_SECRETKEYBYTES {
            return Err(Error::InvalidKeySize {
                expected: CRYPTO_SECRETKEYBYTES,
                actual: secret_key_size,
            });
        }

        // Create buffers for keys
        let mut public_key_buf = [0u8; CRYPTO_PUBLICKEYBYTES];
        let mut secret_key_buf = [0u8; CRYPTO_SECRETKEYBYTES];

        // Generate keypair using Classical McEliece
        let (public_key, secret_key) = if let Some(rng_bytes) = randomness {
            // Use provided randomness with deterministic RNG
            // Use local RNG implementation (non-blocking)
            {
                let mut rng = crate::LibQRng::new_deterministic_from_bytes(rng_bytes);
                keypair(&mut public_key_buf, &mut secret_key_buf, &mut rng)
            }
        } else {
            // Use secure system randomness with local RNG (non-blocking)
            {
                let mut rng = crate::LibQRng::new();
                keypair(&mut public_key_buf, &mut secret_key_buf, &mut rng)
            }
        };

        // Copy key material into KemKeypair-owned buffers; stack buffers are zeroed when
        // `PublicKey` / `SecretKey` drop (zeroize feature).
        Ok(KemKeypair::new(
            Vec::from(public_key.as_array().as_slice()),
            Vec::from(secret_key.as_array().as_slice()),
        ))
    }

    /// Encapsulate using Classical McEliece
    fn encapsulate_cb_kem(
        &self,
        public_key: &KemPublicKey,
        randomness: Option<&[u8]>,
    ) -> Result<(Vec<u8>, Vec<u8>)> {
        // Validate public key size
        if public_key.as_bytes().len() != CRYPTO_PUBLICKEYBYTES {
            return Err(Error::InvalidKeySize {
                expected: CRYPTO_PUBLICKEYBYTES,
                actual: public_key.as_bytes().len(),
            });
        }

        // Create public key from bytes
        let mut public_key_buf = [0u8; CRYPTO_PUBLICKEYBYTES];
        public_key_buf.copy_from_slice(public_key.as_bytes());
        let public_key = PublicKey::from(&mut public_key_buf);

        // Create shared secret buffer
        let mut shared_secret_buf = [0u8; CRYPTO_BYTES];

        // Encapsulate
        let (ciphertext, shared_secret) = if let Some(rng_bytes) = randomness {
            // Use provided randomness with deterministic RNG
            // Use local RNG implementation (non-blocking)
            {
                let mut rng = crate::LibQRng::new_deterministic_from_bytes(rng_bytes);
                encapsulate(&public_key, &mut shared_secret_buf, &mut rng)
            }
        } else {
            // Use secure system randomness with local RNG (non-blocking)
            {
                let mut rng = crate::LibQRng::new();
                encapsulate(&public_key, &mut shared_secret_buf, &mut rng)
            }
        };

        Ok((
            Vec::from(ciphertext.as_array().as_slice()),
            Vec::from(shared_secret.as_array().as_slice()),
        ))
    }

    /// Decapsulate using Classical McEliece
    fn decapsulate_cb_kem(&self, secret_key: &KemSecretKey, ciphertext: &[u8]) -> Result<Vec<u8>> {
        // Validate secret key size
        if secret_key.as_bytes().len() != CRYPTO_SECRETKEYBYTES {
            return Err(Error::InvalidKeySize {
                expected: CRYPTO_SECRETKEYBYTES,
                actual: secret_key.as_bytes().len(),
            });
        }

        // Validate ciphertext size
        if ciphertext.len() != CRYPTO_CIPHERTEXTBYTES {
            return Err(Error::InvalidCiphertextSize {
                expected: CRYPTO_CIPHERTEXTBYTES,
                actual: ciphertext.len(),
            });
        }

        // Create secret key from bytes
        let mut secret_key_buf = [0u8; CRYPTO_SECRETKEYBYTES];
        secret_key_buf.copy_from_slice(secret_key.as_bytes());
        let secret_key = SecretKey::from(&mut secret_key_buf);

        // Create ciphertext from bytes
        let mut ciphertext_buf = [0u8; CRYPTO_CIPHERTEXTBYTES];
        ciphertext_buf.copy_from_slice(ciphertext);
        let ciphertext = Ciphertext::from(ciphertext_buf);

        // Create shared secret buffer
        let mut shared_secret_buf = [0u8; CRYPTO_BYTES];

        // Decapsulate
        let shared_secret = decapsulate(&ciphertext, &secret_key, &mut shared_secret_buf);

        Ok(Vec::from(shared_secret.as_array().as_slice()))
    }
}

#[cfg(feature = "alloc")]
impl CryptoProvider for LibQCbKemProvider {
    fn kem(&self) -> Option<&dyn KemOperations> {
        Some(self)
    }

    fn signature(&self) -> Option<&dyn lib_q_core::api::SignatureOperations> {
        None
    }

    fn hash(&self) -> Option<&dyn lib_q_core::api::HashOperations> {
        None
    }

    fn aead(&self) -> Option<&dyn lib_q_core::api::AeadOperations> {
        None
    }
}

#[cfg(all(test, feature = "alloc"))]
mod tests {
    use super::*;

    /// [`Algorithm`] that matches the single active `cbkem*` feature for this build (see `api.rs`).
    fn compiled_cb_kem_algorithm() -> Algorithm {
        #[cfg(any(feature = "cbkem348864", feature = "cbkem348864f"))]
        {
            Algorithm::CbKem348864
        }
        #[cfg(all(
            not(any(feature = "cbkem348864", feature = "cbkem348864f")),
            any(feature = "cbkem460896", feature = "cbkem460896f"),
        ))]
        {
            Algorithm::CbKem460896
        }
        #[cfg(all(
            not(any(
                feature = "cbkem348864",
                feature = "cbkem348864f",
                feature = "cbkem460896",
                feature = "cbkem460896f",
            )),
            any(feature = "cbkem6688128", feature = "cbkem6688128f"),
        ))]
        {
            Algorithm::CbKem6688128
        }
        #[cfg(all(
            not(any(
                feature = "cbkem348864",
                feature = "cbkem348864f",
                feature = "cbkem460896",
                feature = "cbkem460896f",
                feature = "cbkem6688128",
                feature = "cbkem6688128f",
            )),
            any(feature = "cbkem6960119", feature = "cbkem6960119f"),
        ))]
        {
            Algorithm::CbKem6960119
        }
        #[cfg(all(
            not(any(
                feature = "cbkem348864",
                feature = "cbkem348864f",
                feature = "cbkem460896",
                feature = "cbkem460896f",
                feature = "cbkem6688128",
                feature = "cbkem6688128f",
                feature = "cbkem6960119",
                feature = "cbkem6960119f",
            )),
            any(feature = "cbkem8192128", feature = "cbkem8192128f"),
        ))]
        {
            Algorithm::CbKem8192128
        }
    }

    #[test]
    fn test_provider_creation() {
        let provider = LibQCbKemProvider::new();
        assert!(provider.is_ok(), "Provider should be created successfully");
    }

    #[test]
    fn test_provider_security_validator() {
        let provider = LibQCbKemProvider::new().unwrap();
        let _validator = provider.security_validator();
        // Security validator should be accessible
    }

    #[test]
    fn test_provider_security_validator_mut_accessor() {
        let mut provider = LibQCbKemProvider::new().unwrap();
        let _validator_mut = provider.security_validator_mut();
    }

    #[test]
    fn test_provider_unsupported_algorithm() {
        let provider = LibQCbKemProvider::new().unwrap();
        let result = provider.generate_keypair(Algorithm::Sha3_256, None);
        assert!(
            result.is_err(),
            "Should return error for unsupported algorithm"
        );

        if let Err(Error::InvalidAlgorithm { .. }) = result {
            // Expected error type
        } else {
            panic!("Expected InvalidAlgorithm error");
        }
    }

    #[test]
    fn test_provider_algorithm_routing() {
        let provider = LibQCbKemProvider::new().unwrap();

        // Must match the compiled variant: this crate is built for exactly one `cbkem*` feature.
        let alg = compiled_cb_kem_algorithm();

        provider
            .security_validator()
            .validate_algorithm_category(alg, lib_q_core::api::AlgorithmCategory::Kem)
            .expect("compiled CB-KEM algorithm should be a KEM");

        // This crate is `#![no_std]` (the `std` feature is only a cfg knob), so we cannot spawn
        // a thread with a larger stack. Full `keypair()` for large-parameter variants overflows
        // the default test thread stack in debug builds; exercise it only for the smallest build.
        #[cfg(any(feature = "cbkem348864", feature = "cbkem348864f"))]
        {
            let result = provider.generate_keypair(alg, None);
            match result {
                Ok(_) => {}
                Err(Error::NotImplemented { .. }) => {}
                Err(Error::RandomGenerationFailed { .. }) => {}
                Err(e) => panic!("Unexpected error type: {:?}", e),
            }
        }
    }

    #[test]
    fn test_provider_full_kem_cycle() {
        #[cfg(feature = "std")]
        {
            let provider = LibQCbKemProvider::new().unwrap();

            let alg = compiled_cb_kem_algorithm();

            // Full keygen+encap+decap is extremely expensive for larger parameter sets in debug
            // and can exceed tarpaulin's per-test response window. Execute this end-to-end cycle
            // only for the smallest variants; other variants are still validated by algorithm
            // routing and lower-level known-answer/integration tests.
            #[cfg(any(feature = "cbkem348864", feature = "cbkem348864f"))]
            {
                // Test full KEM cycle for the Classical McEliece variant in this build
                let keypair = provider.generate_keypair(alg, None).unwrap();

                // Test encapsulation
                let (ciphertext, shared_secret1) = provider
                    .encapsulate(alg, &keypair.public_key, None)
                    .unwrap();

                // Test decapsulation
                let shared_secret2 = provider
                    .decapsulate(alg, &keypair.secret_key, &ciphertext)
                    .unwrap();

                // Verify shared secrets match
                assert_eq!(
                    shared_secret1, shared_secret2,
                    "Shared secrets should match"
                );

                // Verify sizes are correct
                assert_eq!(
                    ciphertext.len(),
                    CRYPTO_CIPHERTEXTBYTES,
                    "Classical McEliece ciphertext should be {} bytes",
                    CRYPTO_CIPHERTEXTBYTES
                );
                assert_eq!(
                    shared_secret1.len(),
                    CRYPTO_BYTES,
                    "Shared secret should be {} bytes",
                    CRYPTO_BYTES
                );
            }

            #[cfg(not(any(feature = "cbkem348864", feature = "cbkem348864f")))]
            {
                provider
                    .security_validator()
                    .validate_algorithm_category(alg, lib_q_core::api::AlgorithmCategory::Kem)
                    .expect("compiled CB-KEM algorithm should be a KEM");
            }
        }
    }

    #[test]
    fn test_provider_derive_public_key_is_unsupported() {
        let provider = LibQCbKemProvider::new().unwrap();
        let secret_key = KemSecretKey::new(Vec::new());
        let result = provider.derive_public_key(compiled_cb_kem_algorithm(), &secret_key);
        assert!(matches!(result, Err(Error::UnsupportedOperation { .. })));
    }

    #[test]
    fn test_crypto_provider_trait_exposes_only_kem_operations() {
        let provider = LibQCbKemProvider::new().unwrap();
        let crypto_provider: &dyn CryptoProvider = &provider;
        assert!(crypto_provider.kem().is_some());
        assert!(crypto_provider.signature().is_none());
        assert!(crypto_provider.hash().is_none());
        assert!(crypto_provider.aead().is_none());
    }
}