lib-q-hpke 0.0.5

HPKE implementation 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
//! SHAKE256 AEAD for HPKE (`HpkeAead::Shake256`).
//!
//! Wraps concrete [`lib_q_aead::Shake256Aead`]. HPKE [`crate::aead::traits::Aead::open`]
//! is a thin wrapper over [`Shake256AeadImpl::decrypt_semantic`] (Layer B), mirroring
//! [`super::saturnin::SaturninAeadImpl`].

#[cfg(all(feature = "alloc", feature = "shake256"))]
use alloc::format;
#[cfg(feature = "alloc")]
use alloc::string::String;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;

#[cfg(feature = "shake256")]
use lib_q_aead::Shake256Aead;
#[cfg(feature = "shake256")]
use lib_q_core::{
    Aead,
    AeadDecryptSemantic,
    AeadKey,
    DecryptSemanticOutcome,
    Nonce,
};

use crate::error::{
    AeadOperation,
    HpkeError,
};
use crate::types::*;

/// SHAKE256 AEAD implementation using concrete `lib-q-aead` [`Shake256Aead`].
pub struct Shake256AeadImpl {
    #[cfg(feature = "shake256")]
    aead: Shake256Aead,
}

impl Shake256AeadImpl {
    /// Create a new SHAKE256 AEAD implementation
    pub fn new() -> Result<Self, HpkeError> {
        #[cfg(feature = "shake256")]
        {
            Ok(Self {
                aead: Shake256Aead::new(),
            })
        }

        #[cfg(not(feature = "shake256"))]
        {
            Err(HpkeError::feature_not_enabled("SHAKE256 AEAD support"))
        }
    }

    /// Validate key, nonce, and minimum ciphertext length for SHAKE256 HPKE paths.
    #[cfg(feature = "shake256")]
    fn prepare_shake256_open(
        key: &[u8],
        nonce: &[u8],
        ciphertext: &[u8],
    ) -> Result<(AeadKey, Nonce), HpkeError> {
        if key.len() != 32 {
            return Err(HpkeError::aead_error(
                HpkeAead::Shake256,
                AeadOperation::KeyValidation,
                format!(
                    "Invalid key length for SHAKE256: expected 32 bytes, got {}",
                    key.len()
                ),
            ));
        }

        if key.iter().all(|&b| b == 0) {
            return Err(HpkeError::aead_error(
                HpkeAead::Shake256,
                AeadOperation::KeyValidation,
                "Key material cannot be all zeros",
            ));
        }

        if nonce.len() != 16 {
            return Err(HpkeError::aead_error(
                HpkeAead::Shake256,
                AeadOperation::NonceValidation,
                format!(
                    "Invalid nonce length for SHAKE256: expected 16 bytes, got {}",
                    nonce.len()
                ),
            ));
        }

        if ciphertext.len() < 32 {
            return Err(HpkeError::aead_error(
                HpkeAead::Shake256,
                AeadOperation::CiphertextValidation,
                "Ciphertext too short",
            ));
        }

        Ok((AeadKey::new(key.to_vec()), Nonce::new(nonce.to_vec())))
    }

    /// Layer B decrypt: operational failures are [`Err`]; authentication failure is
    /// [`DecryptSemanticOutcome::AuthenticationFailed`] in the [`Ok`] arm.
    #[cfg(feature = "shake256")]
    pub fn decrypt_semantic(
        &self,
        key: &[u8],
        nonce: &[u8],
        aad: &[u8],
        ciphertext: &[u8],
    ) -> Result<DecryptSemanticOutcome, HpkeError> {
        let (aead_key, aead_nonce) = Self::prepare_shake256_open(key, nonce, ciphertext)?;
        self.aead
            .decrypt_semantic(&aead_key, &aead_nonce, ciphertext, Some(aad))
            .map_err(|e| {
                HpkeError::aead_error(
                    HpkeAead::Shake256,
                    AeadOperation::Open,
                    format!("SHAKE256 semantic decrypt failed: {}", e),
                )
            })
    }
}

impl crate::aead::traits::Aead for Shake256AeadImpl {
    fn seal(
        &self,
        key: &[u8],
        nonce: &[u8],
        aad: &[u8],
        plaintext: &[u8],
    ) -> Result<Vec<u8>, HpkeError> {
        #[cfg(feature = "shake256")]
        {
            if key.len() != 32 {
                return Err(HpkeError::aead_error(
                    HpkeAead::Shake256,
                    AeadOperation::KeyValidation,
                    format!(
                        "Invalid key length for SHAKE256: expected 32 bytes, got {}",
                        key.len()
                    ),
                ));
            }

            if key.iter().all(|&b| b == 0) {
                return Err(HpkeError::aead_error(
                    HpkeAead::Shake256,
                    AeadOperation::KeyValidation,
                    "Key material cannot be all zeros",
                ));
            }

            if nonce.len() != 16 {
                return Err(HpkeError::aead_error(
                    HpkeAead::Shake256,
                    AeadOperation::NonceValidation,
                    format!(
                        "Invalid nonce length for SHAKE256: expected 16 bytes, got {}",
                        nonce.len()
                    ),
                ));
            }

            let aead_key = AeadKey::new(key.to_vec());
            let aead_nonce = Nonce::new(nonce.to_vec());

            self.aead
                .encrypt(&aead_key, &aead_nonce, plaintext, Some(aad))
                .map_err(|e| {
                    HpkeError::aead_error(
                        HpkeAead::Shake256,
                        AeadOperation::Seal,
                        format!("SHAKE256 encryption failed: {}", e),
                    )
                })
        }

        #[cfg(not(feature = "shake256"))]
        {
            Err(HpkeError::feature_not_enabled("SHAKE256 AEAD support"))
        }
    }

    fn open(
        &self,
        key: &[u8],
        nonce: &[u8],
        aad: &[u8],
        ciphertext: &[u8],
    ) -> Result<Vec<u8>, HpkeError> {
        #[cfg(feature = "shake256")]
        {
            match self.decrypt_semantic(key, nonce, aad, ciphertext)? {
                DecryptSemanticOutcome::Success(p) => Ok(Vec::clone(&*p)),
                DecryptSemanticOutcome::AuthenticationFailed => Err(HpkeError::aead_error(
                    HpkeAead::Shake256,
                    AeadOperation::Open,
                    String::from("SHAKE256 authentication failed"),
                )),
            }
        }

        #[cfg(not(feature = "shake256"))]
        {
            Err(HpkeError::feature_not_enabled("SHAKE256 AEAD support"))
        }
    }
}

/// Create a SHAKE256 AEAD implementation
pub fn create_shake256_aead() -> Result<Shake256AeadImpl, HpkeError> {
    Shake256AeadImpl::new()
}

/// Check if SHAKE256 AEAD is available
pub fn is_shake256_available() -> bool {
    #[cfg(feature = "shake256")]
    {
        true
    }
    #[cfg(not(feature = "shake256"))]
    {
        false
    }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "alloc")]
    use alloc::vec;

    use super::*;
    use crate::aead::traits::Aead;

    #[test]
    fn test_shake256_availability() {
        let available = is_shake256_available();
        #[cfg(feature = "shake256")]
        assert!(available);
        #[cfg(not(feature = "shake256"))]
        assert!(!available);
    }

    #[test]
    fn test_shake256_creation() {
        let result = Shake256AeadImpl::new();
        #[cfg(feature = "shake256")]
        assert!(result.is_ok());
        #[cfg(not(feature = "shake256"))]
        assert!(result.is_err());
    }

    #[cfg(feature = "shake256")]
    #[test]
    fn test_shake256_operations() {
        let aead = Shake256AeadImpl::new().unwrap();

        let key = vec![
            0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54,
            0x32, 0x10, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC,
            0xDD, 0xEE, 0xFF, 0x00,
        ];
        let nonce = vec![
            0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54,
            0x32, 0x10,
        ];
        let plaintext = b"Hello, World!";
        let aad = b"metadata";

        let ciphertext = aead.seal(&key, &nonce, aad, plaintext).unwrap();
        assert!(!ciphertext.is_empty());
        assert_ne!(ciphertext, plaintext);

        let decrypted = aead.open(&key, &nonce, aad, &ciphertext).unwrap();
        assert_eq!(decrypted, plaintext);
    }

    #[cfg(feature = "shake256")]
    #[test]
    fn test_shake256_decrypt_semantic_auth_failure() {
        let aead = Shake256AeadImpl::new().unwrap();
        let key = vec![
            0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54,
            0x32, 0x10, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC,
            0xDD, 0xEE, 0xFF, 0x00,
        ];
        let nonce = vec![
            0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54,
            0x32, 0x10,
        ];
        let aad = b"metadata";
        let plaintext = b"Hello, World!";
        let mut ct = aead.seal(&key, &nonce, aad, plaintext).unwrap();
        *ct.last_mut().expect("tag byte") ^= 1;
        let out = aead.decrypt_semantic(&key, &nonce, aad, &ct).unwrap();
        assert_eq!(out, DecryptSemanticOutcome::AuthenticationFailed);
    }

    #[cfg(feature = "shake256")]
    #[test]
    fn test_shake256_invalid_key_length() {
        let aead = Shake256AeadImpl::new().unwrap();

        let invalid_key = vec![1u8; 16];
        let nonce = vec![2u8; 16];
        let plaintext = b"Hello, World!";
        let aad = b"metadata";

        let result = aead.seal(&invalid_key, &nonce, aad, plaintext);
        assert!(result.is_err());

        if let Err(HpkeError::AeadError {
            algorithm,
            operation,
            ..
        }) = result
        {
            assert_eq!(algorithm, HpkeAead::Shake256);
            assert_eq!(operation, AeadOperation::KeyValidation);
        } else {
            panic!("Expected AeadError");
        }
    }

    #[cfg(feature = "shake256")]
    #[test]
    fn test_shake256_invalid_nonce_length() {
        let aead = Shake256AeadImpl::new().unwrap();

        let key = vec![1u8; 32];
        let invalid_nonce = vec![2u8; 12];
        let plaintext = b"Hello, World!";
        let aad = b"metadata";

        let result = aead.seal(&key, &invalid_nonce, aad, plaintext);
        assert!(result.is_err());

        if let Err(HpkeError::AeadError {
            algorithm,
            operation,
            ..
        }) = result
        {
            assert_eq!(algorithm, HpkeAead::Shake256);
            assert_eq!(operation, AeadOperation::NonceValidation);
        } else {
            panic!("Expected AeadError");
        }
    }

    #[cfg(feature = "shake256")]
    #[test]
    fn test_shake256_zero_key() {
        let aead = Shake256AeadImpl::new().unwrap();

        let zero_key = vec![0u8; 32];
        let nonce = vec![2u8; 16];
        let plaintext = b"Hello, World!";
        let aad = b"metadata";

        let result = aead.seal(&zero_key, &nonce, aad, plaintext);
        assert!(result.is_err());

        if let Err(HpkeError::AeadError {
            algorithm,
            operation,
            ..
        }) = result
        {
            assert_eq!(algorithm, HpkeAead::Shake256);
            assert_eq!(operation, AeadOperation::KeyValidation);
        } else {
            panic!("Expected AeadError");
        }
    }

    #[cfg(feature = "shake256")]
    #[test]
    fn test_shake256_authentication_failure() {
        let aead = Shake256AeadImpl::new().unwrap();

        let key = vec![
            0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54,
            0x32, 0x10, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC,
            0xDD, 0xEE, 0xFF, 0x00,
        ];
        let nonce = vec![
            0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54,
            0x32, 0x10,
        ];
        let plaintext = b"Hello, World!";
        let aad = b"metadata";

        let ciphertext = aead.seal(&key, &nonce, aad, plaintext).unwrap();

        let mut tampered = ciphertext.clone();
        tampered[0] ^= 0xFF;

        let result = aead.open(&key, &nonce, aad, &tampered);
        assert!(result.is_err());

        if let Err(HpkeError::AeadError {
            algorithm,
            operation,
            ..
        }) = result
        {
            assert_eq!(algorithm, HpkeAead::Shake256);
            assert_eq!(operation, AeadOperation::Open);
        } else {
            panic!("Expected AeadError");
        }
    }
}