lib-q-core 0.0.4

Core types and traits 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
//! Main lib-Q cryptographic provider implementation
//!
//! This module provides the main LibQCryptoProvider that implements
//! the CryptoProvider trait and delegates to specific operation providers.

#[cfg(feature = "std")]
use super::{
    LibQAeadStubProvider,
    LibQHashProvider,
    LibQKemProvider,
    LibQSignatureProvider,
};
use crate::api::{
    AeadOperations,
    CryptoProvider,
    HashOperations,
    KemOperations,
    SignatureOperations,
};
use crate::error::Result;

/// Main lib-Q cryptographic provider
///
/// This provider implements the CryptoProvider trait and delegates
/// to specific operation providers for each cryptographic operation type.
/// It serves as the main entry point for all lib-Q cryptographic operations.
#[cfg(feature = "std")]
#[derive(Clone)]
pub struct LibQCryptoProvider {
    kem_provider: LibQKemProvider,
    signature_provider: LibQSignatureProvider,
    hash_provider: LibQHashProvider,
    aead_provider: LibQAeadStubProvider,
}

// WASM-compatible version
#[cfg(not(feature = "std"))]
#[derive(Clone)]
pub struct LibQCryptoProvider {
    kem_provider: WasmKemProvider,
    signature_provider: WasmSignatureProvider,
    hash_provider: WasmHashProvider,
    aead_provider: WasmAeadProvider,
}

#[cfg(feature = "std")]
impl LibQCryptoProvider {
    /// Create a new lib-Q cryptographic provider
    ///
    /// # Returns
    ///
    /// A new instance of LibQCryptoProvider with all operation providers initialized.
    ///
    /// # Errors
    ///
    /// Returns an error if any of the operation providers fail to initialize.
    pub fn new() -> Result<Self> {
        Ok(Self {
            kem_provider: LibQKemProvider::new()?,
            signature_provider: LibQSignatureProvider::new()?,
            hash_provider: LibQHashProvider::new()?,
            aead_provider: LibQAeadStubProvider::new()?,
        })
    }

    /// Get the KEM provider
    pub fn kem_provider(&self) -> &LibQKemProvider {
        &self.kem_provider
    }

    /// Get the signature provider
    pub fn signature_provider(&self) -> &LibQSignatureProvider {
        &self.signature_provider
    }

    /// Get the hash provider
    pub fn hash_provider(&self) -> &LibQHashProvider {
        &self.hash_provider
    }

    /// Get the stub AEAD provider (use `lib-q-aead` for real AEAD).
    pub fn aead_provider(&self) -> &LibQAeadStubProvider {
        &self.aead_provider
    }
}

// WASM-compatible implementation
#[cfg(not(feature = "std"))]
impl LibQCryptoProvider {
    /// Create a new lib-Q cryptographic provider (WASM version)
    pub fn new() -> Result<Self> {
        Ok(Self {
            kem_provider: WasmKemProvider::new()?,
            signature_provider: WasmSignatureProvider::new()?,
            hash_provider: WasmHashProvider::new()?,
            aead_provider: WasmAeadProvider::new()?,
        })
    }

    /// Get the KEM provider
    pub fn kem_provider(&self) -> &WasmKemProvider {
        &self.kem_provider
    }

    /// Get the signature provider
    pub fn signature_provider(&self) -> &WasmSignatureProvider {
        &self.signature_provider
    }

    /// Get the hash provider
    pub fn hash_provider(&self) -> &WasmHashProvider {
        &self.hash_provider
    }

    /// Get the AEAD provider
    pub fn aead_provider(&self) -> &WasmAeadProvider {
        &self.aead_provider
    }
}

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

    fn signature(&self) -> Option<&dyn SignatureOperations> {
        Some(&self.signature_provider)
    }

    fn hash(&self) -> Option<&dyn HashOperations> {
        Some(&self.hash_provider)
    }

    fn aead(&self) -> Option<&dyn AeadOperations> {
        Some(&self.aead_provider)
    }
}

#[cfg(not(feature = "std"))]
impl CryptoProvider for LibQCryptoProvider {
    fn kem(&self) -> Option<&dyn KemOperations> {
        Some(&self.kem_provider)
    }

    fn signature(&self) -> Option<&dyn SignatureOperations> {
        Some(&self.signature_provider)
    }

    fn hash(&self) -> Option<&dyn HashOperations> {
        Some(&self.hash_provider)
    }

    fn aead(&self) -> Option<&dyn AeadOperations> {
        Some(&self.aead_provider)
    }
}

// WASM-specific provider implementations
#[cfg(not(feature = "std"))]
use alloc::format;

#[cfg(not(feature = "std"))]
use crate::security::SecurityValidator;
#[cfg(not(feature = "std"))]
use crate::traits::{
    AeadKey,
    KemKeypair,
    KemPublicKey,
    KemSecretKey,
    Nonce,
    SigKeypair,
    SigPublicKey,
    SigSecretKey,
};

#[cfg(not(feature = "std"))]
#[derive(Clone)]
pub struct WasmKemProvider {
    security_validator: SecurityValidator,
}

#[cfg(not(feature = "std"))]
impl WasmKemProvider {
    pub fn new() -> Result<Self> {
        Ok(Self {
            security_validator: SecurityValidator::new()?,
        })
    }
}

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

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

        // Return proper error indicating WASM implementation needed
        Err(crate::error::Error::NotImplemented {
            feature: format!(
                "WASM KEM operations for {} - implementations are provided by the main lib-q crate",
                algorithm
            ),
        })
    }

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

        // Validate public key
        self.security_validator
            .validate_public_key(algorithm, public_key.as_bytes())?;

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

        // Return proper error indicating WASM implementation needed
        Err(crate::error::Error::NotImplemented {
            feature: format!(
                "WASM KEM operations for {} - implementations are provided by the main lib-q crate",
                algorithm
            ),
        })
    }

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

        // Validate secret key
        self.security_validator
            .validate_secret_key(algorithm, secret_key.as_bytes())?;

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

        // Return proper error indicating WASM implementation needed
        Err(crate::error::Error::NotImplemented {
            feature: format!(
                "WASM KEM operations for {} - implementations are provided by the main lib-q crate",
                algorithm
            ),
        })
    }

    fn derive_public_key(
        &self,
        algorithm: crate::api::Algorithm,
        secret_key: &KemSecretKey,
    ) -> Result<KemPublicKey> {
        // Validate algorithm category
        self.security_validator
            .validate_algorithm_category(algorithm, crate::api::AlgorithmCategory::Kem)?;

        // Validate secret key
        self.security_validator
            .validate_secret_key(algorithm, secret_key.as_bytes())?;

        // Return proper error indicating WASM implementation needed
        Err(crate::error::Error::NotImplemented {
            feature: format!(
                "WASM KEM operations for {} - implementations are provided by the main lib-q crate",
                algorithm
            ),
        })
    }
}

#[cfg(not(feature = "std"))]
#[derive(Clone)]
pub struct WasmSignatureProvider {
    security_validator: SecurityValidator,
}

#[cfg(not(feature = "std"))]
impl WasmSignatureProvider {
    pub fn new() -> Result<Self> {
        Ok(Self {
            security_validator: SecurityValidator::new()?,
        })
    }
}

#[cfg(not(feature = "std"))]
impl SignatureOperations for WasmSignatureProvider {
    fn generate_keypair(
        &self,
        algorithm: crate::api::Algorithm,
        randomness: Option<&[u8]>,
    ) -> Result<SigKeypair> {
        // Validate algorithm category
        self.security_validator
            .validate_algorithm_category(algorithm, crate::api::AlgorithmCategory::Signature)?;

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

        // Return proper error indicating WASM implementation needed
        Err(crate::error::Error::NotImplemented {
            feature: format!(
                "WASM Signature operations for {} - implementations are provided by the main lib-q crate",
                algorithm
            ),
        })
    }

    fn sign(
        &self,
        algorithm: crate::api::Algorithm,
        secret_key: &SigSecretKey,
        message: &[u8],
        randomness: Option<&[u8]>,
    ) -> Result<alloc::vec::Vec<u8>> {
        // Validate algorithm category
        self.security_validator
            .validate_algorithm_category(algorithm, crate::api::AlgorithmCategory::Signature)?;

        // Validate secret key
        self.security_validator
            .validate_secret_key(algorithm, secret_key.as_bytes())?;

        // Validate message
        self.security_validator
            .validate_signature_message(message)?;

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

        // Return proper error indicating WASM implementation needed
        Err(crate::error::Error::NotImplemented {
            feature: format!(
                "WASM Signature operations for {} - implementations are provided by the main lib-q crate",
                algorithm
            ),
        })
    }

    fn verify(
        &self,
        algorithm: crate::api::Algorithm,
        public_key: &SigPublicKey,
        message: &[u8],
        signature: &[u8],
    ) -> Result<bool> {
        // Validate algorithm category
        self.security_validator
            .validate_algorithm_category(algorithm, crate::api::AlgorithmCategory::Signature)?;

        // Validate public key
        self.security_validator
            .validate_public_key(algorithm, public_key.as_bytes())?;

        // Validate message
        self.security_validator
            .validate_signature_message(message)?;

        // Validate signature
        self.security_validator
            .validate_signature(algorithm, signature)?;

        // Return proper error indicating WASM implementation needed
        Err(crate::error::Error::NotImplemented {
            feature: format!(
                "WASM Signature operations for {} - implementations are provided by the main lib-q crate",
                algorithm
            ),
        })
    }
}

#[cfg(not(feature = "std"))]
#[derive(Clone)]
pub struct WasmHashProvider {
    security_validator: SecurityValidator,
}

#[cfg(not(feature = "std"))]
impl WasmHashProvider {
    pub fn new() -> Result<Self> {
        Ok(Self {
            security_validator: SecurityValidator::new()?,
        })
    }
}

#[cfg(not(feature = "std"))]
impl HashOperations for WasmHashProvider {
    fn hash(&self, algorithm: crate::api::Algorithm, data: &[u8]) -> Result<alloc::vec::Vec<u8>> {
        // Validate algorithm category
        self.security_validator
            .validate_algorithm_category(algorithm, crate::api::AlgorithmCategory::Hash)?;

        // Validate data
        self.security_validator.validate_hash_input(data)?;

        // Return proper error indicating WASM implementation needed
        Err(crate::error::Error::NotImplemented {
            feature: format!(
                "WASM Hash operations for {} - implementations are provided by the main lib-q crate",
                algorithm
            ),
        })
    }
}

#[cfg(not(feature = "std"))]
#[derive(Clone)]
pub struct WasmAeadProvider {
    security_validator: SecurityValidator,
}

#[cfg(not(feature = "std"))]
impl WasmAeadProvider {
    pub fn new() -> Result<Self> {
        Ok(Self {
            security_validator: SecurityValidator::new()?,
        })
    }
}

#[cfg(not(feature = "std"))]
impl AeadOperations for WasmAeadProvider {
    fn encrypt(
        &self,
        algorithm: crate::api::Algorithm,
        key: &AeadKey,
        nonce: &Nonce,
        plaintext: &[u8],
        associated_data: Option<&[u8]>,
    ) -> Result<alloc::vec::Vec<u8>> {
        // Validate algorithm category
        self.security_validator
            .validate_algorithm_category(algorithm, crate::api::AlgorithmCategory::Aead)?;

        // Validate key
        self.security_validator
            .validate_key_material(key.as_bytes())?;

        // Validate nonce
        self.security_validator.validate_nonce(nonce.as_bytes())?;

        // Validate plaintext
        self.security_validator.validate_aead_message(plaintext)?;

        // Validate associated data if present
        if let Some(ad) = associated_data {
            self.security_validator.validate_aead_message(ad)?;
        }

        // Return proper error indicating WASM implementation needed
        Err(crate::error::Error::NotImplemented {
            feature: format!(
                "WASM AEAD operations for {} - implementations are provided by the main lib-q crate",
                algorithm
            ),
        })
    }

    fn decrypt(
        &self,
        algorithm: crate::api::Algorithm,
        key: &AeadKey,
        nonce: &Nonce,
        ciphertext: &[u8],
        associated_data: Option<&[u8]>,
    ) -> Result<alloc::vec::Vec<u8>> {
        // Validate algorithm category
        self.security_validator
            .validate_algorithm_category(algorithm, crate::api::AlgorithmCategory::Aead)?;

        // Validate key
        self.security_validator
            .validate_key_material(key.as_bytes())?;

        // Validate nonce
        self.security_validator.validate_nonce(nonce.as_bytes())?;

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

        // Validate associated data if present
        if let Some(ad) = associated_data {
            self.security_validator.validate_aead_message(ad)?;
        }

        // Return proper error indicating WASM implementation needed
        Err(crate::error::Error::NotImplemented {
            feature: format!(
                "WASM AEAD operations for {} - implementations are provided by the main lib-q crate",
                algorithm
            ),
        })
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::panic)]

    use super::*;

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

    #[test]
    fn test_libq_provider_default() {
        let provider = match LibQCryptoProvider::new() {
            Ok(p) => p,
            Err(e) => panic!("LibQCryptoProvider::new() failed: {e}"),
        };
        assert!(provider.kem().is_some(), "KEM provider should be available");
        assert!(
            provider.signature().is_some(),
            "Signature provider should be available"
        );
        assert!(
            provider.hash().is_some(),
            "Hash provider should be available"
        );
        assert!(
            provider.aead().is_some(),
            "AEAD provider should be available"
        );
    }

    #[test]
    fn test_libq_provider_operations() {
        let provider = match LibQCryptoProvider::new() {
            Ok(p) => p,
            Err(e) => panic!("LibQCryptoProvider::new() failed: {e}"),
        };

        // Test that all operation providers are accessible
        assert!(provider.kem().is_some());
        assert!(provider.signature().is_some());
        assert!(provider.hash().is_some());
        assert!(provider.aead().is_some());
    }
}