latticearc 0.8.3

Production-ready post-quantum cryptography. Hybrid ML-KEM+X25519 by default, all 4 NIST standards (FIPS 203–206), and FIPS 140-3 backend — one crate, zero unsafe.
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
#![deny(unsafe_code)]
#![deny(missing_docs)]
#![deny(clippy::unwrap_used)]
#![deny(clippy::panic)]

//! AES-GCM (Advanced Encryption Standard - Galois/Counter Mode)
//!
//! Provides AES-GCM-128 and AES-GCM-256 AEAD implementations following NIST SP 800-38D.
//! Uses aws-lc-rs for FIPS 140-3 compliance and optimized performance (AES-NI, AVX2).
//!
//! ## Performance
//!
//! aws-lc-rs provides ~1.5-2x speedup over pure-Rust aes-gcm crate:
//! - AES-256-GCM: ~0.25µs per operation (vs ~0.4µs)
//!
//! ## Security Notes
//!
//! - Nonce MUST be unique for each encryption with same key
//! - Reusing a nonce with same key can lead to catastrophic security failures
//! - Tag verification uses constant-time comparison to prevent timing attacks

use crate::primitives::aead::{
    AES_GCM_128_KEY_LEN, AES_GCM_256_KEY_LEN, AeadCipher, AeadError, Nonce, TAG_LEN, Tag,
};
use crate::primitives::rand::secure_rng;
use aws_lc_rs::aead::{AES_128_GCM, AES_256_GCM, Aad, LessSafeKey, Nonce as AwsNonce, UnboundKey};
use rand::RngCore;
use tracing::instrument;
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};

use crate::primitives::resource_limits::{
    validate_aad_size, validate_decryption_size, validate_encryption_size,
};

// single opaque string for every decrypt failure path. Pattern
// 6 forbids stage-distinguishing error strings on AEAD decrypt — see the
// detailed comment in the macro body below.
const DECRYPTION_FAILED: &str = "decryption failed";

// matching opacity sweep on the AEAD encrypt path. Encrypt
// errors are reachable by callers who probe the configured size cap with
// chosen plaintext lengths — collapsing to a single uniform string blocks
// that side channel without losing operator diagnosability (the per-stage
// cause is preserved via `tracing::debug!` in the higher layers).
const ENCRYPTION_FAILED: &str = "encryption failed";

/// Implements an AES-GCM cipher struct with `AeadCipher` trait and `generate_key()`.
macro_rules! impl_aes_gcm {
    (
        $(#[$meta:meta])*
        $name:ident, $key_len:expr, $algorithm:expr, $label:literal
    ) => {
        $(#[$meta])*
        #[derive(Zeroize, ZeroizeOnDrop)]
        pub struct $name {
            key_bytes: [u8; $key_len],
        }

        impl $name {
            /// Internal raw constructor — length-checked, no weak-key guard.
            /// `pub(crate)` to keep it off the public API surface (the trait
            /// version was previously a public bypass; see `AeadCipher::new`
            /// implementation note).
            #[inline]
            pub(crate) fn new_raw(key: &[u8]) -> Result<Self, AeadError> {
                if key.len() != $key_len {
                    return Err(AeadError::InvalidKeyLength);
                }
                let mut key_bytes = [0u8; $key_len];
                key_bytes.copy_from_slice(key);
                Ok($name { key_bytes })
            }

            /// Construct bypassing the `AeadError::WeakKey` guard.
            ///
            /// Reserved for known-test-vector reproduction (e.g. all-zero
            /// key/IV cases in McGrew & Viega's AES-GCM Test Cases 1 and 2).
            /// Production code MUST use `Self::new` (the `AeadCipher::new`
            /// trait method).
            ///
            /// Gated behind the `kat-test-vectors` Cargo feature so the
            /// bypass is only callable from crates that explicitly opt in.
            ///
            /// # Errors
            /// - `AeadError::InvalidKeyLength` if `key.len() != KEY_LEN`.
            #[cfg(any(test, feature = "kat-test-vectors"))]
            pub fn new_allow_weak_key(key: &[u8]) -> Result<Self, AeadError> {
                Self::new_raw(key)
            }
        }

        impl AeadCipher for $name {
            const KEY_LEN: usize = $key_len;

            #[instrument(level = "debug", skip(key), fields(key_len = key.len()))]
            fn new(key: &[u8]) -> Result<Self, AeadError> {
                if key.len() != Self::KEY_LEN {
                    return Err(AeadError::InvalidKeyLength);
                }
                if crate::primitives::aead::is_all_zero_key(key) {
                    return Err(AeadError::WeakKey);
                }
                Self::new_raw(key)
            }

            fn generate_nonce() -> Nonce {
                let mut nonce = [0u8; 12];
                secure_rng().fill_bytes(&mut nonce);
                nonce
            }

            #[instrument(level = "debug", skip(self, nonce, plaintext, aad), fields(algorithm = $label, plaintext_len = plaintext.len(), has_aad = aad.is_some()))]
            fn encrypt(
                &self,
                nonce: &Nonce,
                plaintext: &[u8],
                aad: Option<&[u8]>,
            ) -> Result<(Vec<u8>, Tag), AeadError> {
                // Pattern 6 opacity sweep on the encrypt path mirrors
                // the decrypt-side sweep. Every adversary-reachable
                // failure (size caps, AEAD seal, post-seal buffer-shape
                // checks) collapses to a single opaque ENCRYPTION_FAILED
                // string. Per-stage cause is preserved via the higher-layer
                // `log_crypto_operation_error!` calls.
                validate_encryption_size(plaintext.len()).map_err(
                    |_e: crate::primitives::resource_limits::ResourceError| {
                        AeadError::EncryptionFailed(ENCRYPTION_FAILED.to_string())
                    },
                )?;

                if let Some(a) = aad {
                    validate_aad_size(a.len()).map_err(|_e| {
                        AeadError::EncryptionFailed(ENCRYPTION_FAILED.to_string())
                    })?;
                }

                let unbound_key = UnboundKey::new($algorithm, &self.key_bytes)
                    .map_err(|_e| AeadError::InvalidKeyLength)?;
                let key = LessSafeKey::new(unbound_key);

                let aws_nonce = AwsNonce::try_assume_unique_for_key(nonce)
                    .map_err(|_e| AeadError::InvalidNonceLength)?;

                let aad = Aad::from(aad.unwrap_or(&[]));

                let mut in_out = Vec::with_capacity(plaintext.len().saturating_add(TAG_LEN));
                in_out.extend_from_slice(plaintext);

                key.seal_in_place_append_tag(aws_nonce, aad, &mut in_out)
                    .map_err(|_e| AeadError::EncryptionFailed(ENCRYPTION_FAILED.to_string()))?;

                if in_out.len() < TAG_LEN {
                    return Err(AeadError::EncryptionFailed(ENCRYPTION_FAILED.to_string()));
                }

                let ct_len = in_out.len().saturating_sub(TAG_LEN);
                let ciphertext = in_out
                    .get(..ct_len)
                    .ok_or_else(|| AeadError::EncryptionFailed(ENCRYPTION_FAILED.to_string()))?
                    .to_vec();
                let mut tag = [0u8; TAG_LEN];
                let tag_slice = in_out
                    .get(ct_len..)
                    .ok_or_else(|| AeadError::EncryptionFailed(ENCRYPTION_FAILED.to_string()))?;
                tag.copy_from_slice(tag_slice);

                Ok((ciphertext, tag))
            }

            #[instrument(level = "debug", skip(self, nonce, ciphertext, tag, aad), fields(algorithm = $label, ciphertext_len = ciphertext.len(), has_aad = aad.is_some()))]
            fn decrypt(
                &self,
                nonce: &Nonce,
                ciphertext: &[u8],
                tag: &Tag,
                aad: Option<&[u8]>,
            ) -> Result<Zeroizing<Vec<u8>>, AeadError> {
                // Pattern 6 opacity sweep. All decrypt failure
                // paths now share the same opaque error string. Size-check
                // branches at the top are still reachable before key init,
                // but they no longer distinguish which size limit was
                // crossed (ciphertext vs AAD vs post-auth shape) so the
                // primitives layer no longer leaks a stage-identifying
                // oracle to direct callers. The InvalidKeyLength /
                // InvalidNonceLength variants below remain distinct because
                // they fire on input shape that an adversary controls
                // explicitly (key/nonce length); the actual open_in_place
                // path is folded into the same opaque string as the
                // post-auth-success buffer-shape check.
                validate_decryption_size(ciphertext.len()).map_err(
                    |_e: crate::primitives::resource_limits::ResourceError| {
                        AeadError::DecryptionFailed(DECRYPTION_FAILED.to_string())
                    },
                )?;

                if let Some(a) = aad {
                    validate_aad_size(a.len()).map_err(|_e| {
                        AeadError::DecryptionFailed(DECRYPTION_FAILED.to_string())
                    })?;
                }

                let unbound_key = UnboundKey::new($algorithm, &self.key_bytes)
                    .map_err(|_e| AeadError::InvalidKeyLength)?;
                let key = LessSafeKey::new(unbound_key);

                let aws_nonce = AwsNonce::try_assume_unique_for_key(nonce)
                    .map_err(|_e| AeadError::InvalidNonceLength)?;

                let aad = Aad::from(aad.unwrap_or(&[]));

                // Wrap `in_out` in Zeroizing so the plaintext residue left in
                // the buffer after `open_in_place` is scrubbed on drop (B2).
                let mut in_out: Zeroizing<Vec<u8>> =
                    Zeroizing::new(Vec::with_capacity(ciphertext.len().saturating_add(TAG_LEN)));
                in_out.extend_from_slice(ciphertext);
                in_out.extend_from_slice(tag);

                let plaintext_len = key
                    .open_in_place(aws_nonce, aad, in_out.as_mut_slice())
                    .map_err(|_e| {
                        AeadError::DecryptionFailed(DECRYPTION_FAILED.to_string())
                    })?
                    .len();

                let plaintext_slice = in_out.get(..plaintext_len).ok_or_else(|| {
                    AeadError::DecryptionFailed(DECRYPTION_FAILED.to_string())
                })?;
                Ok(Zeroizing::new(plaintext_slice.to_vec()))
            }
        }

        impl std::fmt::Debug for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_struct(stringify!($name))
                    .field("key_bytes", &"[REDACTED]")
                    .finish()
            }
        }

        impl subtle::ConstantTimeEq for $name {
            fn ct_eq(&self, other: &Self) -> subtle::Choice {
                self.key_bytes.ct_eq(&other.key_bytes)
            }
        }

        impl $name {
            /// Generate a random key.
            ///
            /// Returns a `Zeroizing` wrapper that automatically zeroes the key on drop.
            #[must_use]
            pub fn generate_key() -> zeroize::Zeroizing<[u8; $key_len]> {
                let mut key = zeroize::Zeroizing::new([0u8; $key_len]);
                secure_rng().fill_bytes(&mut *key);
                key
            }
        }
    };
}

impl_aes_gcm!(
    /// AES-GCM-128 cipher (128-bit key).
    ///
    /// Uses AES-GCM with a 128-bit key following NIST SP 800-38D via aws-lc-rs.
    AesGcm128, AES_GCM_128_KEY_LEN, &AES_128_GCM, "AES-GCM-128"
);

impl_aes_gcm!(
    /// AES-GCM-256 cipher (256-bit key).
    ///
    /// Uses AES-GCM with a 256-bit key following NIST SP 800-38D via aws-lc-rs.
    AesGcm256, AES_GCM_256_KEY_LEN, &AES_256_GCM, "AES-GCM-256"
);

#[cfg(test)]
#[expect(clippy::unwrap_used, reason = "Tests use unwrap for simplicity")]
#[expect(clippy::panic, reason = "Tests use panic! for error case validation")]
mod tests {
    use super::*;

    #[test]
    fn test_aes_gcm_128_key_generation_succeeds() {
        let key1 = AesGcm128::generate_key();
        let key2 = AesGcm128::generate_key();
        assert_eq!(key1.len(), AES_GCM_128_KEY_LEN);
        assert_eq!(key2.len(), AES_GCM_128_KEY_LEN);
        // Keys should be different (with very high probability)
        assert_ne!(key1, key2);
    }

    #[test]
    fn test_aes_gcm_128_invalid_key_length_fails() {
        let key = [0u8; 8]; // Wrong length
        let result = AesGcm128::new(&key);
        assert!(result.is_err());
        if let Err(AeadError::InvalidKeyLength) = result {
            // Expected error - no length information exposed
        } else {
            panic!("Expected InvalidKeyLength error");
        }
    }

    #[test]
    fn test_aes_gcm_256_key_generation_succeeds() {
        let key1 = AesGcm256::generate_key();
        let key2 = AesGcm256::generate_key();
        assert_eq!(key1.len(), AES_GCM_256_KEY_LEN);
        assert_eq!(key2.len(), AES_GCM_256_KEY_LEN);
        // Keys should be different (with very high probability)
        assert_ne!(key1, key2);
    }

    #[test]
    fn test_aes_gcm_256_invalid_key_length_fails() {
        let key = [0u8; 16]; // Wrong length
        let result = AesGcm256::new(&key);
        assert!(result.is_err());
        if let Err(AeadError::InvalidKeyLength) = result {
            // Expected error - no length information exposed
        } else {
            panic!("Expected InvalidKeyLength error");
        }
    }

    #[test]
    fn test_aes_gcm_128_encrypt_decrypt_roundtrip() {
        let key = AesGcm128::generate_key();
        let cipher = AesGcm128::new(&*key).unwrap();
        let nonce = AesGcm128::generate_nonce();
        let plaintext = b"Hello, World!";

        let (ciphertext, tag) = cipher.encrypt(&nonce, plaintext, None).unwrap();
        let decrypted = cipher.decrypt(&nonce, &ciphertext, &tag, None).unwrap();

        assert_eq!(plaintext, decrypted.as_slice());
    }

    #[test]
    fn test_aes_gcm_256_encrypt_decrypt_roundtrip() {
        let key = AesGcm256::generate_key();
        let cipher = AesGcm256::new(&*key).unwrap();
        let nonce = AesGcm256::generate_nonce();
        let plaintext = b"Hello, World!";

        let (ciphertext, tag) = cipher.encrypt(&nonce, plaintext, None).unwrap();
        let decrypted = cipher.decrypt(&nonce, &ciphertext, &tag, None).unwrap();

        assert_eq!(plaintext, decrypted.as_slice());
    }

    #[test]
    fn test_aes_gcm_256_seal_generates_fresh_nonce_per_call() {
        let key = AesGcm256::generate_key();
        let cipher = AesGcm256::new(&*key).unwrap();
        let plaintext = b"seal must generate a fresh nonce per call";

        let (nonce1, ct1, tag1) = cipher.seal(plaintext, None).unwrap();
        let (nonce2, ct2, tag2) = cipher.seal(plaintext, None).unwrap();

        // Same key + same plaintext must produce distinct nonces → distinct ciphertexts.
        assert_ne!(nonce1, nonce2, "seal() must generate a fresh nonce per call");
        assert_ne!(ct1, ct2, "fresh nonces must produce distinct ciphertexts");
        assert_ne!(tag1, tag2, "fresh nonces must produce distinct tags");

        // Both sealed blobs decrypt correctly.
        let pt1 = cipher.decrypt(&nonce1, &ct1, &tag1, None).unwrap();
        let pt2 = cipher.decrypt(&nonce2, &ct2, &tag2, None).unwrap();
        assert_eq!(plaintext, pt1.as_slice());
        assert_eq!(plaintext, pt2.as_slice());
    }

    #[test]
    fn test_aes_gcm_128_seal_roundtrip_with_aad() {
        let key = AesGcm128::generate_key();
        let cipher = AesGcm128::new(&*key).unwrap();
        let plaintext = b"seal with aad";
        let aad = b"context";

        let (nonce, ct, tag) = cipher.seal(plaintext, Some(aad)).unwrap();
        let decrypted = cipher.decrypt(&nonce, &ct, &tag, Some(aad)).unwrap();
        assert_eq!(plaintext, decrypted.as_slice());
    }

    #[test]
    fn test_aes_gcm_128_with_aad_roundtrip() {
        let key = AesGcm128::generate_key();
        let cipher = AesGcm128::new(&*key).unwrap();
        let nonce = AesGcm128::generate_nonce();
        let plaintext = b"Secret data";
        let aad = b"Additional authenticated data";

        let (ciphertext, tag) = cipher.encrypt(&nonce, plaintext, Some(aad)).unwrap();
        let decrypted = cipher.decrypt(&nonce, &ciphertext, &tag, Some(aad)).unwrap();

        assert_eq!(plaintext, decrypted.as_slice());
    }

    #[test]
    fn test_aes_gcm_128_with_aad_verification_failure_fails() {
        let key = AesGcm128::generate_key();
        let cipher = AesGcm128::new(&*key).unwrap();
        let nonce = AesGcm128::generate_nonce();
        let plaintext = b"Secret data";
        let aad = b"Correct AAD";

        let (ciphertext, tag) = cipher.encrypt(&nonce, plaintext, Some(aad)).unwrap();

        // Try to decrypt with wrong AAD
        let wrong_aad = b"Wrong AAD";
        let result = cipher.decrypt(&nonce, &ciphertext, &tag, Some(wrong_aad));

        assert!(result.is_err());
        if let Err(AeadError::DecryptionFailed(_)) = result {
            // Expected
        } else {
            panic!("Expected DecryptionFailed error");
        }
    }

    #[test]
    fn test_aes_gcm_128_invalid_tag_fails() {
        let key = AesGcm128::generate_key();
        let cipher = AesGcm128::new(&*key).unwrap();
        let nonce = AesGcm128::generate_nonce();
        let plaintext = b"Secret data";

        let (ciphertext, mut tag) = cipher.encrypt(&nonce, plaintext, None).unwrap();

        // Corrupt the tag
        tag[0] ^= 0xFF;

        let result = cipher.decrypt(&nonce, &ciphertext, &tag, None);

        assert!(result.is_err());
        if let Err(AeadError::DecryptionFailed(_)) = result {
            // Expected
        } else {
            panic!("Expected DecryptionFailed error");
        }
    }

    #[test]
    fn test_aes_gcm_constant_time_tag_verification_is_correct() {
        let tag1 = [1u8; 16];
        let tag2 = [1u8; 16];
        let tag3 = [2u8; 16];

        assert!(super::super::verify_tag_constant_time(&tag1, &tag2));
        assert!(!super::super::verify_tag_constant_time(&tag1, &tag3));
    }

    #[test]
    fn test_aes_gcm_zeroize_data_clears_bytes_succeeds() {
        let mut data = vec![0xFF; 100];
        super::super::zeroize_data(&mut data);
        assert_eq!(data, vec![0u8; 100]);
    }

    #[test]
    fn test_aes_gcm_128_empty_plaintext_roundtrip() {
        let key = AesGcm128::generate_key();
        let cipher = AesGcm128::new(&*key).unwrap();
        let nonce = AesGcm128::generate_nonce();
        let plaintext = b"";

        let (ciphertext, tag) = cipher.encrypt(&nonce, plaintext, None).unwrap();
        let decrypted = cipher.decrypt(&nonce, &ciphertext, &tag, None).unwrap();

        assert_eq!(plaintext, decrypted.as_slice());
        assert_eq!(ciphertext.len(), 0);
        assert_eq!(tag.len(), TAG_LEN);
    }

    #[test]
    fn test_aes_gcm_256_empty_plaintext_roundtrip() {
        let key = AesGcm256::generate_key();
        let cipher = AesGcm256::new(&*key).unwrap();
        let nonce = AesGcm256::generate_nonce();
        let plaintext = b"";

        let (ciphertext, tag) = cipher.encrypt(&nonce, plaintext, None).unwrap();
        let decrypted = cipher.decrypt(&nonce, &ciphertext, &tag, None).unwrap();

        assert_eq!(plaintext, decrypted.as_slice());
        assert_eq!(ciphertext.len(), 0);
        assert_eq!(tag.len(), TAG_LEN);
    }

    #[test]
    fn test_aes_gcm_128_large_plaintext_roundtrip() {
        let key = AesGcm128::generate_key();
        let cipher = AesGcm128::new(&*key).unwrap();
        let nonce = AesGcm128::generate_nonce();
        let plaintext = vec![0xAB; 1024 * 1024]; // 1MB

        let (ciphertext, tag) = cipher.encrypt(&nonce, &plaintext, None).unwrap();
        let decrypted = cipher.decrypt(&nonce, &ciphertext, &tag, None).unwrap();

        assert_eq!(plaintext, decrypted.as_slice());
        assert_eq!(ciphertext.len(), 1024 * 1024);
        assert_eq!(tag.len(), TAG_LEN);
    }

    #[test]
    fn test_aes_gcm_256_large_plaintext_roundtrip() {
        let key = AesGcm256::generate_key();
        let cipher = AesGcm256::new(&*key).unwrap();
        let nonce = AesGcm256::generate_nonce();
        let plaintext = vec![0xAB; 1024 * 1024]; // 1MB

        let (ciphertext, tag) = cipher.encrypt(&nonce, &plaintext, None).unwrap();
        let decrypted = cipher.decrypt(&nonce, &ciphertext, &tag, None).unwrap();

        assert_eq!(plaintext, decrypted.as_slice());
        assert_eq!(ciphertext.len(), 1024 * 1024);
        assert_eq!(tag.len(), TAG_LEN);
    }

    #[test]
    fn test_aes_gcm_128_corrupted_ciphertext_fails() {
        let key = AesGcm128::generate_key();
        let cipher = AesGcm128::new(&*key).unwrap();
        let nonce = AesGcm128::generate_nonce();
        let plaintext = b"Secret data";

        let (mut ciphertext, tag) = cipher.encrypt(&nonce, plaintext, None).unwrap();

        // Corrupt the ciphertext
        if let Some(last) = ciphertext.last_mut() {
            *last ^= 0xFF;
        }

        let result = cipher.decrypt(&nonce, &ciphertext, &tag, None);

        assert!(result.is_err());
        if let Err(AeadError::DecryptionFailed(_)) = result {
            // Expected
        } else {
            panic!("Expected DecryptionFailed error");
        }
    }

    #[test]
    fn test_aes_gcm_256_with_aad_roundtrip() {
        let key = AesGcm256::generate_key();
        let cipher = AesGcm256::new(&*key).unwrap();
        let nonce = AesGcm256::generate_nonce();
        let plaintext = b"Secret data";
        let aad = b"Additional authenticated data";

        let (ciphertext, tag) = cipher.encrypt(&nonce, plaintext, Some(aad)).unwrap();
        let decrypted = cipher.decrypt(&nonce, &ciphertext, &tag, Some(aad)).unwrap();

        assert_eq!(plaintext, decrypted.as_slice());
    }

    #[test]
    fn test_aes_gcm_128_multiple_encryptions_all_roundtrip() {
        let key = AesGcm128::generate_key();
        let cipher = AesGcm128::new(&*key).unwrap();

        for i in 0..100 {
            let nonce = AesGcm128::generate_nonce();
            let plaintext = format!("Message {}", i);
            let (ciphertext, tag) = cipher.encrypt(&nonce, plaintext.as_bytes(), None).unwrap();
            let decrypted = cipher.decrypt(&nonce, &ciphertext, &tag, None).unwrap();
            assert_eq!(plaintext.as_bytes(), decrypted.as_slice());
        }
    }

    #[test]
    fn test_aes_gcm_256_multiple_encryptions_all_roundtrip() {
        let key = AesGcm256::generate_key();
        let cipher = AesGcm256::new(&*key).unwrap();

        for i in 0..100 {
            let nonce = AesGcm256::generate_nonce();
            let plaintext = format!("Message {}", i);
            let (ciphertext, tag) = cipher.encrypt(&nonce, plaintext.as_bytes(), None).unwrap();
            let decrypted = cipher.decrypt(&nonce, &ciphertext, &tag, None).unwrap();
            assert_eq!(plaintext.as_bytes(), decrypted.as_slice());
        }
    }

    // the previous comment here claimed
    // "NIST test vectors may produce different tags because aws-lc-rs
    // uses hardware-accelerated implementations that may have subtle
    // differences in intermediate computations while still producing
    // correct results." That was **factually incorrect** — aws-lc-rs
    // is FIPS 140-3 validated and produces bit-exact NIST KAT outputs.
    // The comment was a rationalization for not wiring KATs in this
    // file rather than a true description of the backend.
    //
    // Real NIST AES-GCM KAT vectors (CAVP-derived) live in the
    // `latticearc-tests` integration crate
    // (`tests/tests/fips_kat_aead.rs`, `AES_128_GCM_VECTORS` /
    // `AES_256_GCM_VECTORS` plus `run_aes_128_gcm_kat` /
    // `run_aes_256_gcm_kat` helpers). The src-level tests below stay
    // roundtrip-only **by design** — kept fast, kept self-contained,
    // no multi-KiB hard-coded vector blobs in primitive source. The
    // KAT crate is the authoritative cross-validation surface.
    #[test]
    fn test_aes_gcm_128_roundtrip_consistency_roundtrip() {
        // Roundtrip-only by design — see comment block above.
        let key: [u8; 16] = [
            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
            0x0e, 0x0f,
        ];
        let nonce: [u8; 12] =
            [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
        let plaintext: &[u8] = b"Test message for AES-128-GCM";
        let aad: &[u8] = b"Additional data";

        let cipher = AesGcm128::new(&key).unwrap();
        let (ciphertext, tag) = cipher.encrypt(&nonce, plaintext, Some(aad)).unwrap();

        // Verify decryption works
        let decrypted = cipher.decrypt(&nonce, &ciphertext, &tag, Some(aad)).unwrap();
        assert_eq!(plaintext, decrypted.as_slice());
    }

    #[test]
    fn test_aes_gcm_256_roundtrip_consistency_roundtrip() {
        let key: [u8; 32] = [
            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
            0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
            0x1c, 0x1d, 0x1e, 0x1f,
        ];
        let nonce: [u8; 12] =
            [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
        let plaintext: &[u8] = b"Test message for AES-256-GCM";
        let aad: &[u8] = b"Additional data";

        let cipher = AesGcm256::new(&key).unwrap();
        let (ciphertext, tag) = cipher.encrypt(&nonce, plaintext, Some(aad)).unwrap();

        // Verify decryption works
        let decrypted = cipher.decrypt(&nonce, &ciphertext, &tag, Some(aad)).unwrap();
        assert_eq!(plaintext, decrypted.as_slice());
    }

    #[test]
    fn test_aes_gcm_128_encryption_size_limit_has_correct_size() {
        let key = AesGcm128::generate_key();
        let cipher = AesGcm128::new(&*key).unwrap();
        let nonce = AesGcm128::generate_nonce();

        // Try to encrypt data exceeding 100MB limit (101MB)
        let plaintext = vec![0xAB; 101 * 1024 * 1024];

        let result = cipher.encrypt(&nonce, &plaintext, None);
        assert!(result.is_err(), "Should fail with resource limit exceeded");

        // Pattern 6 opacity sweep collapsed every encrypt
        // failure to the same opaque "encryption failed" string, so this
        // test now only asserts the variant shape.
        assert!(
            matches!(result, Err(AeadError::EncryptionFailed(_))),
            "Expected EncryptionFailed variant, got {result:?}"
        );
    }

    #[test]
    fn test_aes_gcm_256_decryption_size_limit_has_correct_size() {
        let key = AesGcm256::generate_key();
        let cipher = AesGcm256::new(&*key).unwrap();
        let nonce = AesGcm256::generate_nonce();

        // Try to decrypt data exceeding 100MB limit
        let ciphertext = vec![0xCD; 101 * 1024 * 1024];
        let tag = [0u8; TAG_LEN];

        let result = cipher.decrypt(&nonce, &ciphertext, &tag, None);
        assert!(result.is_err(), "Should fail with resource limit exceeded");

        // Pattern 6 opacity sweep collapsed every decrypt
        // failure to the same opaque "decryption failed" string, so this
        // test now only asserts the variant shape.
        assert!(
            matches!(result, Err(AeadError::DecryptionFailed(_))),
            "Expected DecryptionFailed variant, got {result:?}"
        );
    }
}