lib-q-hqc 0.0.4

Post-Quantum HQC (Hamming Quasi-Cyclic) KEM for lib-Q
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
//! HQC Correct Implementation
//!
//! This module provides the correct HQC implementation based on the reference specification.
//! It implements HQC-1, HQC-3, and HQC-5 with proper Reed-Solomon + Reed-Muller concatenated codes.

use core::fmt;

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "alloc")]
use alloc::vec::Vec;

use crate::hqc_kem::{
    HqcKem,
    HqcKemCiphertext,
    HqcKemError,
    HqcKemPublicKey,
    HqcKemSecretKey,
    HqcKemSharedSecret,
};
use crate::params_correct::{
    Hqc1Params,
    Hqc3Params,
    Hqc5Params,
    HqcParams,
};

/// HQC core trait following libQ patterns
pub trait HqcCore<P: HqcParams>: Clone + fmt::Debug + PartialEq {
    /// The public key type for this HQC instance
    type PublicKey: Clone + fmt::Debug + PartialEq;
    /// The secret key type for this HQC instance
    type SecretKey: Clone + fmt::Debug + PartialEq;
    /// The ciphertext type for this HQC instance
    type Ciphertext: Clone + fmt::Debug + PartialEq;
    /// The shared secret type for this HQC instance
    type SharedSecret: Clone + fmt::Debug + PartialEq;

    /// Generate a new (secret key, public key) pair
    fn generate_keypair<R: rand_core::CryptoRng + ?Sized>(
        rng: &mut R,
    ) -> Result<(Self::SecretKey, Self::PublicKey), HqcError>;

    /// Encapsulate a shared secret to the public key
    fn encapsulate<R: rand_core::CryptoRng + ?Sized>(
        public_key: &Self::PublicKey,
        rng: &mut R,
    ) -> Result<(Self::Ciphertext, Self::SharedSecret), HqcError>;

    /// Decapsulate the shared secret using the secret key
    fn decapsulate<R: rand_core::CryptoRng + ?Sized>(
        secret_key: &Self::SecretKey,
        ciphertext: &Self::Ciphertext,
    ) -> Result<Self::SharedSecret, HqcError>;

    /// Derive public key from secret key
    fn derive_public_key(secret_key: &Self::SecretKey) -> Result<Self::PublicKey, HqcError>;
}

/// HQC-1 implementation
#[derive(Debug, Clone, PartialEq)]
pub struct Hqc1;

impl HqcCore<Hqc1Params> for Hqc1 {
    type PublicKey = Hqc1PublicKey;
    type SecretKey = Hqc1SecretKey;
    type Ciphertext = Hqc1Ciphertext;
    type SharedSecret = Hqc1SharedSecret;

    fn generate_keypair<R: rand_core::CryptoRng + ?Sized>(
        rng: &mut R,
    ) -> Result<(Self::SecretKey, Self::PublicKey), HqcError> {
        let kem = HqcKem::<Hqc1Params>::new().map_err(HqcError::KemError)?;
        let (public_key, secret_key) = kem.keygen(rng).map_err(HqcError::KemError)?;

        Ok((
            Hqc1SecretKey::new(secret_key),
            Hqc1PublicKey::new(public_key),
        ))
    }

    fn encapsulate<R: rand_core::CryptoRng + ?Sized>(
        public_key: &Self::PublicKey,
        rng: &mut R,
    ) -> Result<(Self::Ciphertext, Self::SharedSecret), HqcError> {
        let kem = HqcKem::<Hqc1Params>::new().map_err(HqcError::KemError)?;
        let (ciphertext, shared_secret) = kem
            .encapsulate(&public_key.kem_public_key, rng)
            .map_err(HqcError::KemError)?;

        Ok((
            Hqc1Ciphertext::new(ciphertext),
            Hqc1SharedSecret::new(shared_secret),
        ))
    }

    fn decapsulate<R: rand_core::CryptoRng + ?Sized>(
        secret_key: &Self::SecretKey,
        ciphertext: &Self::Ciphertext,
    ) -> Result<Self::SharedSecret, HqcError> {
        let kem = HqcKem::<Hqc1Params>::new().map_err(HqcError::KemError)?;
        let shared_secret = kem
            .decapsulate(&secret_key.kem_secret_key, &ciphertext.kem_ciphertext)
            .map_err(HqcError::KemError)?;

        Ok(Hqc1SharedSecret::new(shared_secret))
    }

    fn derive_public_key(secret_key: &Self::SecretKey) -> Result<Self::PublicKey, HqcError> {
        // Extract the public key from the secret key
        let (ek_pke, _dk_pke, _sigma, _seed_kem) = secret_key.kem_secret_key.parse();
        Ok(Hqc1PublicKey::new(HqcKemPublicKey::new(ek_pke)))
    }
}

/// HQC-3 implementation
#[derive(Debug, Clone, PartialEq)]
pub struct Hqc3;

impl HqcCore<Hqc3Params> for Hqc3 {
    type PublicKey = Hqc3PublicKey;
    type SecretKey = Hqc3SecretKey;
    type Ciphertext = Hqc3Ciphertext;
    type SharedSecret = Hqc3SharedSecret;

    fn generate_keypair<R: rand_core::CryptoRng + ?Sized>(
        rng: &mut R,
    ) -> Result<(Self::SecretKey, Self::PublicKey), HqcError> {
        let kem = HqcKem::<Hqc3Params>::new().map_err(HqcError::KemError)?;
        let (public_key, secret_key) = kem.keygen(rng).map_err(HqcError::KemError)?;

        Ok((
            Hqc3SecretKey::new(secret_key),
            Hqc3PublicKey::new(public_key),
        ))
    }

    fn encapsulate<R: rand_core::CryptoRng + ?Sized>(
        public_key: &Self::PublicKey,
        rng: &mut R,
    ) -> Result<(Self::Ciphertext, Self::SharedSecret), HqcError> {
        let kem = HqcKem::<Hqc3Params>::new().map_err(HqcError::KemError)?;
        let (ciphertext, shared_secret) = kem
            .encapsulate(&public_key.kem_public_key, rng)
            .map_err(HqcError::KemError)?;

        Ok((
            Hqc3Ciphertext::new(ciphertext),
            Hqc3SharedSecret::new(shared_secret),
        ))
    }

    fn decapsulate<R: rand_core::CryptoRng + ?Sized>(
        secret_key: &Self::SecretKey,
        ciphertext: &Self::Ciphertext,
    ) -> Result<Self::SharedSecret, HqcError> {
        let kem = HqcKem::<Hqc3Params>::new().map_err(HqcError::KemError)?;
        let shared_secret = kem
            .decapsulate(&secret_key.kem_secret_key, &ciphertext.kem_ciphertext)
            .map_err(HqcError::KemError)?;

        Ok(Hqc3SharedSecret::new(shared_secret))
    }

    fn derive_public_key(secret_key: &Self::SecretKey) -> Result<Self::PublicKey, HqcError> {
        let (ek_pke, _dk_pke, _sigma, _seed_kem) = secret_key.kem_secret_key.parse();
        Ok(Hqc3PublicKey::new(HqcKemPublicKey::new(ek_pke)))
    }
}

/// HQC-5 implementation
#[derive(Debug, Clone, PartialEq)]
pub struct Hqc5;

impl HqcCore<Hqc5Params> for Hqc5 {
    type PublicKey = Hqc5PublicKey;
    type SecretKey = Hqc5SecretKey;
    type Ciphertext = Hqc5Ciphertext;
    type SharedSecret = Hqc5SharedSecret;

    fn generate_keypair<R: rand_core::CryptoRng + ?Sized>(
        rng: &mut R,
    ) -> Result<(Self::SecretKey, Self::PublicKey), HqcError> {
        let kem = HqcKem::<Hqc5Params>::new().map_err(HqcError::KemError)?;
        let (public_key, secret_key) = kem.keygen(rng).map_err(HqcError::KemError)?;

        Ok((
            Hqc5SecretKey::new(secret_key),
            Hqc5PublicKey::new(public_key),
        ))
    }

    fn encapsulate<R: rand_core::CryptoRng + ?Sized>(
        public_key: &Self::PublicKey,
        rng: &mut R,
    ) -> Result<(Self::Ciphertext, Self::SharedSecret), HqcError> {
        let kem = HqcKem::<Hqc5Params>::new().map_err(HqcError::KemError)?;
        let (ciphertext, shared_secret) = kem
            .encapsulate(&public_key.kem_public_key, rng)
            .map_err(HqcError::KemError)?;

        Ok((
            Hqc5Ciphertext::new(ciphertext),
            Hqc5SharedSecret::new(shared_secret),
        ))
    }

    fn decapsulate<R: rand_core::CryptoRng + ?Sized>(
        secret_key: &Self::SecretKey,
        ciphertext: &Self::Ciphertext,
    ) -> Result<Self::SharedSecret, HqcError> {
        let kem = HqcKem::<Hqc5Params>::new().map_err(HqcError::KemError)?;
        let shared_secret = kem
            .decapsulate(&secret_key.kem_secret_key, &ciphertext.kem_ciphertext)
            .map_err(HqcError::KemError)?;

        Ok(Hqc5SharedSecret::new(shared_secret))
    }

    fn derive_public_key(secret_key: &Self::SecretKey) -> Result<Self::PublicKey, HqcError> {
        let (ek_pke, _dk_pke, _sigma, _seed_kem) = secret_key.kem_secret_key.parse();
        Ok(Hqc5PublicKey::new(HqcKemPublicKey::new(ek_pke)))
    }
}

// HQC-1 Types
#[derive(Debug, Clone, PartialEq)]
pub struct Hqc1PublicKey {
    kem_public_key: HqcKemPublicKey<Hqc1Params>,
}

impl Hqc1PublicKey {
    pub fn new(kem_public_key: HqcKemPublicKey<Hqc1Params>) -> Self {
        Self { kem_public_key }
    }

    pub fn as_bytes(&self) -> &[u8] {
        self.kem_public_key.as_bytes()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Hqc1SecretKey {
    kem_secret_key: HqcKemSecretKey<Hqc1Params>,
}

impl Hqc1SecretKey {
    pub fn new(kem_secret_key: HqcKemSecretKey<Hqc1Params>) -> Self {
        Self { kem_secret_key }
    }

    #[cfg(feature = "alloc")]
    pub fn as_bytes(&self) -> Vec<u8> {
        self.kem_secret_key.as_bytes()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Hqc1Ciphertext {
    kem_ciphertext: HqcKemCiphertext<Hqc1Params>,
}

impl Hqc1Ciphertext {
    pub fn new(kem_ciphertext: HqcKemCiphertext<Hqc1Params>) -> Self {
        Self { kem_ciphertext }
    }

    #[cfg(feature = "alloc")]
    pub fn as_bytes(&self) -> Vec<u8> {
        self.kem_ciphertext.as_bytes()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Hqc1SharedSecret {
    kem_shared_secret: HqcKemSharedSecret<Hqc1Params>,
}

impl Hqc1SharedSecret {
    pub fn new(kem_shared_secret: HqcKemSharedSecret<Hqc1Params>) -> Self {
        Self { kem_shared_secret }
    }

    pub fn as_bytes(&self) -> &[u8] {
        self.kem_shared_secret.as_bytes()
    }
}

// HQC-3 Types
#[derive(Debug, Clone, PartialEq)]
pub struct Hqc3PublicKey {
    kem_public_key: HqcKemPublicKey<Hqc3Params>,
}

impl Hqc3PublicKey {
    pub fn new(kem_public_key: HqcKemPublicKey<Hqc3Params>) -> Self {
        Self { kem_public_key }
    }

    pub fn as_bytes(&self) -> &[u8] {
        self.kem_public_key.as_bytes()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Hqc3SecretKey {
    kem_secret_key: HqcKemSecretKey<Hqc3Params>,
}

impl Hqc3SecretKey {
    pub fn new(kem_secret_key: HqcKemSecretKey<Hqc3Params>) -> Self {
        Self { kem_secret_key }
    }

    #[cfg(feature = "alloc")]
    pub fn as_bytes(&self) -> Vec<u8> {
        self.kem_secret_key.as_bytes()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Hqc3Ciphertext {
    kem_ciphertext: HqcKemCiphertext<Hqc3Params>,
}

impl Hqc3Ciphertext {
    pub fn new(kem_ciphertext: HqcKemCiphertext<Hqc3Params>) -> Self {
        Self { kem_ciphertext }
    }

    #[cfg(feature = "alloc")]
    pub fn as_bytes(&self) -> Vec<u8> {
        self.kem_ciphertext.as_bytes()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Hqc3SharedSecret {
    kem_shared_secret: HqcKemSharedSecret<Hqc3Params>,
}

impl Hqc3SharedSecret {
    pub fn new(kem_shared_secret: HqcKemSharedSecret<Hqc3Params>) -> Self {
        Self { kem_shared_secret }
    }

    pub fn as_bytes(&self) -> &[u8] {
        self.kem_shared_secret.as_bytes()
    }
}

// HQC-5 Types
#[derive(Debug, Clone, PartialEq)]
pub struct Hqc5PublicKey {
    kem_public_key: HqcKemPublicKey<Hqc5Params>,
}

impl Hqc5PublicKey {
    pub fn new(kem_public_key: HqcKemPublicKey<Hqc5Params>) -> Self {
        Self { kem_public_key }
    }

    pub fn as_bytes(&self) -> &[u8] {
        self.kem_public_key.as_bytes()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Hqc5SecretKey {
    kem_secret_key: HqcKemSecretKey<Hqc5Params>,
}

impl Hqc5SecretKey {
    pub fn new(kem_secret_key: HqcKemSecretKey<Hqc5Params>) -> Self {
        Self { kem_secret_key }
    }

    #[cfg(feature = "alloc")]
    pub fn as_bytes(&self) -> Vec<u8> {
        self.kem_secret_key.as_bytes()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Hqc5Ciphertext {
    kem_ciphertext: HqcKemCiphertext<Hqc5Params>,
}

impl Hqc5Ciphertext {
    pub fn new(kem_ciphertext: HqcKemCiphertext<Hqc5Params>) -> Self {
        Self { kem_ciphertext }
    }

    #[cfg(feature = "alloc")]
    pub fn as_bytes(&self) -> Vec<u8> {
        self.kem_ciphertext.as_bytes()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Hqc5SharedSecret {
    kem_shared_secret: HqcKemSharedSecret<Hqc5Params>,
}

impl Hqc5SharedSecret {
    pub fn new(kem_shared_secret: HqcKemSharedSecret<Hqc5Params>) -> Self {
        Self { kem_shared_secret }
    }

    pub fn as_bytes(&self) -> &[u8] {
        self.kem_shared_secret.as_bytes()
    }
}

/// HQC error types
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HqcError {
    KemError(HqcKemError),
    InvalidParameters,
    InvalidKey,
    InvalidCiphertext,
    DecryptionFailed,
}

impl fmt::Display for HqcError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HqcError::KemError(e) => write!(f, "KEM error: {}", e),
            HqcError::InvalidParameters => write!(f, "Invalid parameters"),
            HqcError::InvalidKey => write!(f, "Invalid key"),
            HqcError::InvalidCiphertext => write!(f, "Invalid ciphertext"),
            HqcError::DecryptionFailed => write!(f, "Decryption failed"),
        }
    }
}

impl From<HqcKemError> for HqcError {
    fn from(error: HqcKemError) -> Self {
        HqcError::KemError(error)
    }
}

/*
#[cfg(test)]
mod tests {
    use super::*;
    // Note: Using a simple RNG for testing - in production use proper crypto RNG

    #[test]
    fn test_hqc1_full_cycle() {
        // Simple test RNG - in production use proper crypto RNG
        let mut rng = [42u8; 32];

        // Generate key pair
        let (secret_key, public_key) = Hqc1::generate_keypair(&mut rng).unwrap();

        // Encapsulate
        let (ciphertext, shared_secret) = Hqc1::encapsulate(&public_key, &mut rng).unwrap();

        // Decapsulate
        let decapsulated_secret = Hqc1::decapsulate::<[u8; 32]>(&secret_key, &ciphertext).unwrap();

        // Verify
        assert_eq!(shared_secret.as_bytes(), decapsulated_secret.as_bytes());
    }

    #[test]
    fn test_hqc3_full_cycle() {
        // Simple test RNG - in production use proper crypto RNG
        let mut rng = [42u8; 32];

        // Generate key pair
        let (secret_key, public_key) = Hqc3::generate_keypair(&mut rng).unwrap();

        // Encapsulate
        let (ciphertext, shared_secret) = Hqc3::encapsulate(&public_key, &mut rng).unwrap();

        // Decapsulate
        let decapsulated_secret = Hqc3::decapsulate::<[u8; 32]>(&secret_key, &ciphertext).unwrap();

        // Verify
        assert_eq!(shared_secret.as_bytes(), decapsulated_secret.as_bytes());
    }

    #[test]
    fn test_hqc5_full_cycle() {
        // Simple test RNG - in production use proper crypto RNG
        let mut rng = [42u8; 32];

        // Generate key pair
        let (secret_key, public_key) = Hqc5::generate_keypair(&mut rng).unwrap();

        // Encapsulate
        let (ciphertext, shared_secret) = Hqc5::encapsulate(&public_key, &mut rng).unwrap();

        // Decapsulate
        let decapsulated_secret = Hqc5::decapsulate::<[u8; 32]>(&secret_key, &ciphertext).unwrap();

        // Verify
        assert_eq!(shared_secret.as_bytes(), decapsulated_secret.as_bytes());
    }

    #[test]
    fn test_derive_public_key() {
        // Simple test RNG - in production use proper crypto RNG
        let mut rng = [42u8; 32];

        // Generate key pair
        let (secret_key, original_public_key) = Hqc1::generate_keypair(&mut rng).unwrap();

        // Derive public key from secret key
        let derived_public_key = Hqc1::derive_public_key(&secret_key).unwrap();

        // Verify they match
        assert_eq!(original_public_key.as_bytes(), derived_public_key.as_bytes());
    }

    #[test]
    fn test_key_sizes() {
        // Simple test RNG - in production use proper crypto RNG
        let mut rng = [42u8; 32];

        // Test HQC-1 key sizes
        let (secret_key, public_key) = Hqc1::generate_keypair(&mut rng).unwrap();
        assert_eq!(public_key.as_bytes().len(), Hqc1Params::PUBLIC_KEY_BYTES);
        assert_eq!(secret_key.as_bytes().len(), Hqc1Params::SECRET_KEY_BYTES);

        // Test HQC-3 key sizes
        let (secret_key, public_key) = Hqc3::generate_keypair(&mut rng).unwrap();
        assert_eq!(public_key.as_bytes().len(), Hqc3Params::PUBLIC_KEY_BYTES);
        assert_eq!(secret_key.as_bytes().len(), Hqc3Params::SECRET_KEY_BYTES);

        // Test HQC-5 key sizes
        let (secret_key, public_key) = Hqc5::generate_keypair(&mut rng).unwrap();
        assert_eq!(public_key.as_bytes().len(), Hqc5Params::PUBLIC_KEY_BYTES);
        assert_eq!(secret_key.as_bytes().len(), Hqc5Params::SECRET_KEY_BYTES);
    }
}
*/

// Type aliases for convenience
pub type Hqc128Kem = HqcKem<Hqc1Params>;
pub type Hqc192Kem = HqcKem<Hqc3Params>;
pub type Hqc256Kem = HqcKem<Hqc5Params>;