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
//! Common traits for lib-Q cryptographic operations

#[cfg(feature = "alloc")]
use zeroize::{
    Zeroize,
    ZeroizeOnDrop,
};

use crate::error::Result;

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

#[cfg(feature = "wasm")]
use js_sys::Uint8Array;
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;

/// Trait for key encapsulation mechanisms
pub trait Kem {
    /// Generate a keypair
    fn generate_keypair(&self) -> Result<KemKeypair>;

    /// Encapsulate a shared secret
    #[cfg(feature = "alloc")]
    fn encapsulate(&self, public_key: &KemPublicKey) -> Result<(Vec<u8>, Vec<u8>)>;
    #[cfg(not(feature = "alloc"))]
    fn encapsulate(&self, public_key: &KemPublicKey) -> Result<(&'static [u8], &'static [u8])>;

    /// Decapsulate a shared secret
    #[cfg(feature = "alloc")]
    fn decapsulate(&self, secret_key: &KemSecretKey, ciphertext: &[u8]) -> Result<Vec<u8>>;
    #[cfg(not(feature = "alloc"))]
    fn decapsulate(&self, secret_key: &KemSecretKey, ciphertext: &[u8]) -> Result<&'static [u8]>;

    /// Derive public key from secret key
    #[cfg(feature = "alloc")]
    fn derive_public_key(&self, secret_key: &KemSecretKey) -> Result<KemPublicKey>;
    #[cfg(not(feature = "alloc"))]
    fn derive_public_key(&self, secret_key: &KemSecretKey) -> Result<KemPublicKey>;

    /// Authenticated encapsulation (RFC 9180 AuthEncap)
    #[cfg(feature = "alloc")]
    fn auth_encapsulate(
        &self,
        sender_sk: &KemSecretKey,
        recipient_pk: &KemPublicKey,
    ) -> Result<(Vec<u8>, Vec<u8>)>;
    #[cfg(not(feature = "alloc"))]
    fn auth_encapsulate(
        &self,
        sender_sk: &KemSecretKey,
        recipient_pk: &KemPublicKey,
    ) -> Result<(&'static [u8], &'static [u8])>;

    /// Authenticated decapsulation (RFC 9180 AuthDecap)
    #[cfg(feature = "alloc")]
    fn auth_decapsulate(
        &self,
        recipient_sk: &KemSecretKey,
        ciphertext: &[u8],
        sender_pk: &KemPublicKey,
    ) -> Result<Vec<u8>>;
    #[cfg(not(feature = "alloc"))]
    fn auth_decapsulate(
        &self,
        recipient_sk: &KemSecretKey,
        ciphertext: &[u8],
        sender_pk: &KemPublicKey,
    ) -> Result<&'static [u8]>;
}

/// Trait for digital signatures
pub trait Signature {
    /// Generate a keypair
    fn generate_keypair(&self) -> Result<SigKeypair>;

    /// Sign a message
    #[cfg(feature = "alloc")]
    fn sign(&self, secret_key: &SigSecretKey, message: &[u8]) -> Result<Vec<u8>>;
    #[cfg(not(feature = "alloc"))]
    fn sign(&self, secret_key: &SigSecretKey, message: &[u8]) -> Result<&'static [u8]>;

    /// Verify a signature
    fn verify(&self, public_key: &SigPublicKey, message: &[u8], signature: &[u8]) -> Result<bool>;
}

/// Trait for hash functions
pub trait Hash {
    /// Hash data
    #[cfg(feature = "alloc")]
    fn hash(&self, data: &[u8]) -> Result<Vec<u8>>;
    #[cfg(not(feature = "alloc"))]
    fn hash(&self, data: &[u8]) -> Result<&'static [u8]>;

    /// Get the output size in bytes
    fn output_size(&self) -> usize;
}

/// Trait for authenticated encryption with associated data (AEAD).
///
/// # Verification timing and the `Result` API
///
/// Implementations **should** complete symmetric decryption (or an equivalent fixed
/// schedule) before branching on authentication success, so bulk **cryptographic** cost does
/// not depend on whether the tag or equivalent check passes. Tag and MAC comparisons
/// **must** use constant-time equality on secret material (for example
/// [`Utils::constant_time_compare`](crate::Utils::constant_time_compare)).
///
/// A normal Rust [`Result`] still maps verification to [`Result::Ok`] versus
/// [`Result::Err`]: that discriminant is visible to control flow and wall-clock timing at
/// this API boundary. Callers that must hide verification outcome from remote observers
/// need a higher layer (fixed-latency envelope, scheduling isolation, or a non-`Result`
/// cryptographic API designed for that threat model). When the `alloc` feature is enabled,
/// see also `crate::security::timing` for related utilities, and [`crate::AeadDecryptSemantic`] /
/// [`DecryptSemanticOutcome`](crate::DecryptSemanticOutcome) for **Layer B** (semantic
/// outcome without plaintext on `AuthenticationFailed`; see `docs/adr/003-aead-decrypt-layers.md`).
pub trait Aead {
    /// Encrypt data
    #[cfg(feature = "alloc")]
    fn encrypt(
        &self,
        key: &AeadKey,
        nonce: &Nonce,
        plaintext: &[u8],
        associated_data: Option<&[u8]>,
    ) -> Result<Vec<u8>>;
    #[cfg(not(feature = "alloc"))]
    fn encrypt(
        &self,
        key: &AeadKey,
        nonce: &Nonce,
        plaintext: &[u8],
        associated_data: Option<&[u8]>,
    ) -> Result<&'static [u8]>;

    /// Decrypt data
    #[cfg(feature = "alloc")]
    fn decrypt(
        &self,
        key: &AeadKey,
        nonce: &Nonce,
        ciphertext: &[u8],
        associated_data: Option<&[u8]>,
    ) -> Result<Vec<u8>>;
    #[cfg(not(feature = "alloc"))]
    fn decrypt(
        &self,
        key: &AeadKey,
        nonce: &Nonce,
        ciphertext: &[u8],
        associated_data: Option<&[u8]>,
    ) -> Result<&'static [u8]>;
}

// Key types
/// KEM keypair with automatic memory zeroization
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub struct KemKeypair {
    #[cfg_attr(feature = "wasm", wasm_bindgen(skip))]
    pub public_key: KemPublicKey,
    #[cfg_attr(feature = "wasm", wasm_bindgen(skip))]
    pub secret_key: KemSecretKey,
}

/// KEM public key
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub struct KemPublicKey {
    #[cfg_attr(feature = "wasm", wasm_bindgen(skip))]
    #[cfg(feature = "alloc")]
    pub data: Vec<u8>,
    #[cfg(not(feature = "alloc"))]
    pub data: &'static [u8],
}

/// KEM secret key with automatic memory zeroization
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub struct KemSecretKey {
    #[cfg_attr(feature = "wasm", wasm_bindgen(skip))]
    #[cfg(feature = "alloc")]
    pub data: Vec<u8>,
    #[cfg_attr(feature = "wasm", wasm_bindgen(skip))]
    #[cfg(not(feature = "alloc"))]
    pub data: &'static [u8],
}

#[cfg(feature = "alloc")]
impl Zeroize for KemSecretKey {
    fn zeroize(&mut self) {
        self.data.zeroize();
    }
}

#[cfg(feature = "alloc")]
impl ZeroizeOnDrop for KemSecretKey {}

/// Signature keypair with automatic memory zeroization
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub struct SigKeypair {
    #[cfg_attr(feature = "wasm", wasm_bindgen(skip))]
    pub public_key: SigPublicKey,
    #[cfg_attr(feature = "wasm", wasm_bindgen(skip))]
    pub secret_key: SigSecretKey,
}

/// Signature public key
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub struct SigPublicKey {
    #[cfg_attr(feature = "wasm", wasm_bindgen(skip))]
    #[cfg(feature = "alloc")]
    pub data: Vec<u8>,
    #[cfg_attr(feature = "wasm", wasm_bindgen(skip))]
    #[cfg(not(feature = "alloc"))]
    pub data: &'static [u8],
}

/// Signature secret key with automatic memory zeroization
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub struct SigSecretKey {
    #[cfg_attr(feature = "wasm", wasm_bindgen(skip))]
    #[cfg(feature = "alloc")]
    pub data: Vec<u8>,
    #[cfg_attr(feature = "wasm", wasm_bindgen(skip))]
    #[cfg(not(feature = "alloc"))]
    pub data: &'static [u8],
}

#[cfg(feature = "alloc")]
impl Zeroize for SigSecretKey {
    fn zeroize(&mut self) {
        self.data.zeroize();
    }
}

#[cfg(feature = "alloc")]
impl ZeroizeOnDrop for SigSecretKey {}

/// AEAD key
pub struct AeadKey {
    #[cfg(feature = "alloc")]
    pub data: Vec<u8>,
    #[cfg(not(feature = "alloc"))]
    pub data: &'static [u8],
}

#[cfg(feature = "alloc")]
impl Zeroize for AeadKey {
    fn zeroize(&mut self) {
        self.data.zeroize();
    }
}

#[cfg(feature = "alloc")]
impl ZeroizeOnDrop for AeadKey {}

/// Nonce for AEAD operations
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Nonce {
    #[cfg(feature = "alloc")]
    pub data: Vec<u8>,
    #[cfg(not(feature = "alloc"))]
    pub data: &'static [u8],
}

// Implementations for key types
impl KemKeypair {
    #[cfg(feature = "alloc")]
    pub fn new(public_key: Vec<u8>, secret_key: Vec<u8>) -> Self {
        Self {
            public_key: KemPublicKey { data: public_key },
            secret_key: KemSecretKey { data: secret_key },
        }
    }

    #[cfg(not(feature = "alloc"))]
    pub fn new(public_key: &'static [u8], secret_key: &'static [u8]) -> Self {
        Self {
            public_key: KemPublicKey { data: public_key },
            secret_key: KemSecretKey { data: secret_key },
        }
    }

    pub fn public_key(&self) -> &KemPublicKey {
        &self.public_key
    }

    pub fn secret_key(&self) -> &KemSecretKey {
        &self.secret_key
    }
}

#[cfg(feature = "wasm")]
#[wasm_bindgen]
impl KemKeypair {
    /// Create a new KEM keypair from bytes for WASM
    #[wasm_bindgen(constructor)]
    pub fn new_wasm(public_key: Vec<u8>, secret_key: Vec<u8>) -> KemKeypair {
        Self::new(public_key, secret_key)
    }

    /// Get the public key as bytes for WASM
    pub fn public_key_bytes(&self) -> Vec<u8> {
        self.public_key.data.to_vec()
    }

    /// Copy the secret key into a new `Uint8Array` for WASM (avoids returning an owned non-zeroizing `Vec<u8>`).
    pub fn secret_key_bytes(&self) -> Uint8Array {
        let n =
            u32::try_from(self.secret_key.data.len()).expect("KEM secret key length fits in u32");
        let out = Uint8Array::new_with_length(n);
        out.copy_from(&self.secret_key.data);
        out
    }
}

impl SigKeypair {
    #[cfg(feature = "alloc")]
    pub fn new(public_key: Vec<u8>, secret_key: Vec<u8>) -> Self {
        Self {
            public_key: SigPublicKey { data: public_key },
            secret_key: SigSecretKey { data: secret_key },
        }
    }

    #[cfg(not(feature = "alloc"))]
    pub fn new(public_key: &'static [u8], secret_key: &'static [u8]) -> Self {
        Self {
            public_key: SigPublicKey { data: public_key },
            secret_key: SigSecretKey { data: secret_key },
        }
    }

    pub fn public_key(&self) -> &SigPublicKey {
        &self.public_key
    }

    pub fn secret_key(&self) -> &SigSecretKey {
        &self.secret_key
    }
}

impl KemPublicKey {
    #[cfg(feature = "alloc")]
    pub fn new(data: Vec<u8>) -> Self {
        Self { data }
    }

    #[cfg(not(feature = "alloc"))]
    pub fn new(data: &'static [u8]) -> Self {
        Self { data }
    }

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

#[cfg(feature = "wasm")]
#[wasm_bindgen]
impl KemPublicKey {
    /// Create a new KEM public key from bytes for WASM
    #[wasm_bindgen(constructor)]
    pub fn new_from_bytes(data: Vec<u8>) -> KemPublicKey {
        Self::new(data)
    }

    /// Get the key data as bytes for WASM
    pub fn bytes(&self) -> Vec<u8> {
        self.data.to_vec()
    }
}

impl KemSecretKey {
    #[cfg(feature = "alloc")]
    pub fn new(data: Vec<u8>) -> Self {
        Self { data }
    }

    #[cfg(not(feature = "alloc"))]
    pub fn new(data: &'static [u8]) -> Self {
        Self { data }
    }

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

#[cfg(feature = "wasm")]
#[wasm_bindgen]
impl KemSecretKey {
    /// Create a new KEM secret key from bytes for WASM
    #[wasm_bindgen(constructor)]
    pub fn new_from_bytes(data: Vec<u8>) -> KemSecretKey {
        Self::new(data)
    }

    /// Copy the key material into a new `Uint8Array` for WASM (avoids returning an owned non-zeroizing `Vec<u8>`).
    pub fn bytes(&self) -> Uint8Array {
        let n = u32::try_from(self.data.len()).expect("KEM secret key length fits in u32");
        let out = Uint8Array::new_with_length(n);
        out.copy_from(&self.data);
        out
    }
}

impl SigPublicKey {
    #[cfg(feature = "alloc")]
    pub fn new(data: Vec<u8>) -> Self {
        Self { data }
    }

    #[cfg(not(feature = "alloc"))]
    pub fn new(data: &'static [u8]) -> Self {
        Self { data }
    }

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

impl SigSecretKey {
    #[cfg(feature = "alloc")]
    pub fn new(data: Vec<u8>) -> Self {
        Self { data }
    }

    #[cfg(not(feature = "alloc"))]
    pub fn new(data: &'static [u8]) -> Self {
        Self { data }
    }

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

impl AeadKey {
    #[cfg(feature = "alloc")]
    pub fn new(data: Vec<u8>) -> Self {
        Self { data }
    }

    #[cfg(not(feature = "alloc"))]
    pub fn new(data: &'static [u8]) -> Self {
        Self { data }
    }

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

impl Nonce {
    #[cfg(feature = "alloc")]
    pub fn new(data: Vec<u8>) -> Self {
        Self { data }
    }

    #[cfg(not(feature = "alloc"))]
    pub fn new(data: &'static [u8]) -> Self {
        Self { data }
    }

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