latticearc 0.5.0

Production-ready post-quantum cryptography. Hybrid ML-KEM+X25519 by default, all 4 NIST standards (FIPS 203–206), post-quantum TLS, 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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
//! AES-GCM symmetric encryption operations
//!
//! This module provides AES-256-GCM authenticated encryption.
//!
//! ## Security Considerations
//!
//! **Nonce Management:** This implementation uses random 96-bit nonces. Due to birthday
//! paradox, random nonces have a collision probability of approximately 2^-32 after 2^32
//! encryptions (4 billion operations). For high-volume applications, consider using
//! counter-based nonces or rotating keys.
//!
//! **Key Length:** Keys must be exactly 32 bytes for AES-256. Any other key length is
//! rejected with an error.
//!
//! ## Unified API with SecurityMode
//!
//! All cryptographic operations use `SecurityMode` to specify verification behavior:
//!
//! ```no_run
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use latticearc::unified_api::{encrypt_aes_gcm, SecurityMode, VerifiedSession};
//! # let data = b"example data";
//! # let key = [0u8; 32];
//! # let pk = [0u8; 32];
//! # let sk = [0u8; 32];
//! # let session = VerifiedSession::establish(&pk, &sk)?;
//!
//! // With Zero Trust verification (recommended)
//! let encrypted = encrypt_aes_gcm(data, &key, SecurityMode::Verified(&session))?;
//!
//! // Without verification (opt-out)
//! let encrypted = encrypt_aes_gcm(data, &key, SecurityMode::Unverified)?;
//! # Ok(())
//! # }
//! ```

use crate::{
    log_crypto_operation_complete, log_crypto_operation_error, log_crypto_operation_start,
};
use tracing::debug;
use zeroize::Zeroizing;

use crate::primitives::aead::aes_gcm::AesGcm256;
use crate::primitives::aead::{AeadCipher, TAG_LEN};

use crate::unified_api::CoreConfig;
use crate::unified_api::error::{CoreError, Result};
use crate::unified_api::zero_trust::SecurityMode;

// ============================================================================
// Internal Implementation — delegates to primitives::aead::AesGcm256
// ============================================================================

/// Internal implementation of AES-GCM encryption.
///
/// Delegates to [`encrypt_aes_gcm_with_aad_internal`] with empty AAD.
pub(crate) fn encrypt_aes_gcm_internal(data: &[u8], key: &[u8]) -> Result<Vec<u8>> {
    encrypt_aes_gcm_with_aad_internal(data, key, b"")
}

/// Internal implementation of AES-GCM encryption with Additional Authenticated Data (AAD).
///
/// Delegates to `primitives::aead::AesGcm256` so all callers benefit from the
/// same hardening (zero-key warning, `ZeroizeOnDrop`).
///
/// Wire format: `nonce(12) || ciphertext || tag(16)`.
pub(crate) fn encrypt_aes_gcm_with_aad_internal(
    data: &[u8],
    key: &[u8],
    aad: &[u8],
) -> Result<Vec<u8>> {
    log_crypto_operation_start!(
        "aes_gcm_encrypt_aad",
        algorithm = "AES-256-GCM",
        data_len = data.len(),
        aad_len = aad.len()
    );

    if key.len() != 32 {
        let err = CoreError::InvalidKeyLength { expected: 32, actual: key.len() };
        log_crypto_operation_error!("aes_gcm_encrypt_aad", err);
        return Err(err);
    }

    // Delegate to the primitives AesGcm256 (includes zero-key warning, ZeroizeOnDrop)
    let cipher = AesGcm256::new(key).map_err(|e| {
        let err = CoreError::EncryptionFailed(format!("Failed to create AES key: {e}"));
        log_crypto_operation_error!("aes_gcm_encrypt_aad", err);
        err
    })?;

    let nonce = AesGcm256::generate_nonce();
    let aad_opt = if aad.is_empty() { None } else { Some(aad) };

    let (ciphertext, tag) = cipher.encrypt(&nonce, data, aad_opt).map_err(|e| {
        let err = CoreError::EncryptionFailed(e.to_string());
        log_crypto_operation_error!("aes_gcm_encrypt_aad", err);
        err
    })?;

    // Wire format: nonce(12) || ciphertext || tag(16)
    let mut result =
        Vec::with_capacity(nonce.len().saturating_add(ciphertext.len()).saturating_add(TAG_LEN));
    result.extend_from_slice(&nonce);
    result.extend_from_slice(&ciphertext);
    result.extend_from_slice(&tag);

    log_crypto_operation_complete!(
        "aes_gcm_encrypt_aad",
        algorithm = "AES-256-GCM",
        ciphertext_len = result.len()
    );
    debug!(
        data_len = data.len(),
        aad_len = aad.len(),
        ciphertext_len = result.len(),
        "AES-256-GCM encryption with AAD completed"
    );

    Ok(result)
}

/// Internal implementation of AES-GCM decryption with Additional Authenticated Data (AAD).
///
/// Delegates to `primitives::aead::AesGcm256` so all callers benefit from the
/// same hardening (zero-key warning, `ZeroizeOnDrop`).
pub(crate) fn decrypt_aes_gcm_with_aad_internal(
    encrypted_data: &[u8],
    key: &[u8],
    aad: &[u8],
) -> Result<Zeroizing<Vec<u8>>> {
    log_crypto_operation_start!(
        "aes_gcm_decrypt_aad",
        algorithm = "AES-256-GCM",
        encrypted_len = encrypted_data.len(),
        aad_len = aad.len()
    );

    // Minimum: 12 (nonce) + 16 (tag) = 28 bytes
    if encrypted_data.len() < 12 + TAG_LEN {
        let err =
            CoreError::InvalidInput("Data too short for AES-GCM (need nonce + tag)".to_string());
        log_crypto_operation_error!("aes_gcm_decrypt_aad", err);
        return Err(err);
    }

    if key.len() != 32 {
        let err = CoreError::InvalidKeyLength { expected: 32, actual: key.len() };
        log_crypto_operation_error!("aes_gcm_decrypt_aad", err);
        return Err(err);
    }

    // Delegate to the primitives AesGcm256 (includes zero-key warning, ZeroizeOnDrop)
    let cipher = AesGcm256::new(key).map_err(|e| {
        let err = CoreError::DecryptionFailed(format!("Failed to create AES key: {e}"));
        log_crypto_operation_error!("aes_gcm_decrypt_aad", err);
        err
    })?;

    // Parse wire format: nonce(12) || ciphertext || tag(16)
    let (nonce_slice, ct_and_tag) = encrypted_data.split_at(12);
    let nonce: [u8; 12] = nonce_slice.try_into().map_err(|e| {
        let err = CoreError::InvalidNonce(format!("Nonce must be 12 bytes: {e}"));
        log_crypto_operation_error!("aes_gcm_decrypt_aad", err);
        err
    })?;

    let ct_len = ct_and_tag.len().saturating_sub(TAG_LEN);
    let ciphertext = ct_and_tag
        .get(..ct_len)
        .ok_or_else(|| CoreError::DecryptionFailed("Invalid ciphertext length".to_string()))?;
    let tag_slice = ct_and_tag
        .get(ct_len..)
        .ok_or_else(|| CoreError::DecryptionFailed("Invalid tag offset".to_string()))?;
    let tag: [u8; TAG_LEN] = tag_slice
        .try_into()
        .map_err(|_e| CoreError::DecryptionFailed("Tag must be 16 bytes".to_string()))?;

    let aad_opt = if aad.is_empty() { None } else { Some(aad) };

    let result = cipher.decrypt(&nonce, ciphertext, &tag, aad_opt).map_err(|_aead_err| {
        // SECURITY: Opaque error per SP 800-38D §5.2.2
        let err = CoreError::DecryptionFailed("decryption failed".to_string());
        log_crypto_operation_error!("aes_gcm_decrypt_aad", err);
        err
    })?;

    log_crypto_operation_complete!(
        "aes_gcm_decrypt_aad",
        algorithm = "AES-256-GCM",
        plaintext_len = result.len()
    );
    debug!(
        encrypted_len = encrypted_data.len(),
        aad_len = aad.len(),
        plaintext_len = result.len(),
        "AES-256-GCM decryption with AAD completed"
    );

    Ok(result)
}

/// Delegates to [`decrypt_aes_gcm_with_aad_internal`] with empty AAD.
pub(crate) fn decrypt_aes_gcm_internal(
    encrypted_data: &[u8],
    key: &[u8],
) -> Result<Zeroizing<Vec<u8>>> {
    decrypt_aes_gcm_with_aad_internal(encrypted_data, key, b"")
}

// ============================================================================
// Unified API with SecurityMode
// ============================================================================

/// Encrypt data using AES-256-GCM with configurable security mode.
///
/// Uses `SecurityMode` to specify verification behavior:
/// - `SecurityMode::Verified(&session)`: Validates session before encryption
/// - `SecurityMode::Unverified`: Skips session validation
///
/// # Example
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use latticearc::unified_api::{encrypt_aes_gcm, SecurityMode, VerifiedSession};
/// # let data = b"example data";
/// # let key = [0u8; 32];
/// # let pk = [0u8; 32];
/// # let sk = [0u8; 32];
/// # let session = VerifiedSession::establish(&pk, &sk)?;
///
/// // With Zero Trust verification (recommended)
/// let encrypted = encrypt_aes_gcm(data, &key, SecurityMode::Verified(&session))?;
///
/// // Without verification (opt-out)
/// let encrypted = encrypt_aes_gcm(data, &key, SecurityMode::Unverified)?;
/// # Ok(())
/// # }
/// ```
///
/// # Key Requirements
///
/// The `key` parameter must be exactly 32 bytes for AES-256-GCM.
/// Any other key length returns an error.
///
/// # Errors
///
/// Returns an error if:
/// - The session has expired (`CoreError::SessionExpired`) when using `Verified` mode
/// - The key length is not exactly 32 bytes
/// - Random nonce generation fails
/// - The encryption operation fails
#[inline]
pub fn encrypt_aes_gcm(data: &[u8], key: &[u8], mode: SecurityMode) -> Result<Vec<u8>> {
    mode.validate()?;
    encrypt_aes_gcm_internal(data, key)
}

/// Decrypt data using AES-256-GCM with configurable security mode.
///
/// Uses `SecurityMode` to specify verification behavior:
/// - `SecurityMode::Verified(&session)`: Validates session before decryption
/// - `SecurityMode::Unverified`: Skips session validation
///
/// # Example
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use latticearc::unified_api::{decrypt_aes_gcm, SecurityMode, VerifiedSession};
/// # let encrypted = vec![0u8; 44]; // nonce (12) + ciphertext (16) + tag (16)
/// # let key = [0u8; 32];
/// # let pk = [0u8; 32];
/// # let sk = [0u8; 32];
/// # let session = VerifiedSession::establish(&pk, &sk)?;
///
/// // With Zero Trust verification (recommended)
/// let decrypted = decrypt_aes_gcm(&encrypted, &key, SecurityMode::Verified(&session))?;
///
/// // Without verification (opt-out)
/// let decrypted = decrypt_aes_gcm(&encrypted, &key, SecurityMode::Unverified)?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - The session has expired (`CoreError::SessionExpired`) when using `Verified` mode
/// - The encrypted data is shorter than 12 bytes (nonce size)
/// - The key length is less than 32 bytes
/// - The decryption operation fails (e.g., authentication tag mismatch)
#[inline]
pub fn decrypt_aes_gcm(
    encrypted_data: &[u8],
    key: &[u8],
    mode: SecurityMode,
) -> Result<Zeroizing<Vec<u8>>> {
    mode.validate()?;
    decrypt_aes_gcm_internal(encrypted_data, key)
}

/// Encrypt data using AES-256-GCM with configuration and configurable security mode.
///
/// # Key Requirements
///
/// The `key` parameter must be exactly 32 bytes for AES-256-GCM.
/// Any other key length returns an error.
///
/// # Errors
///
/// Returns an error if:
/// - The session has expired when using `Verified` mode
/// - The configuration validation fails
/// - The key length is not exactly 32 bytes
/// - The encryption operation fails
#[inline]
pub fn encrypt_aes_gcm_with_config(
    data: &[u8],
    key: &[u8],
    config: &CoreConfig,
    mode: SecurityMode,
) -> Result<Vec<u8>> {
    mode.validate()?;
    config.validate()?;
    encrypt_aes_gcm_internal(data, key)
}

/// Decrypt data using AES-256-GCM with configuration and configurable security mode.
///
/// # Errors
///
/// Returns an error if:
/// - The session has expired when using `Verified` mode
/// - The configuration validation fails
/// - The encrypted data or key is invalid
/// - The decryption operation fails
#[inline]
pub fn decrypt_aes_gcm_with_config(
    encrypted_data: &[u8],
    key: &[u8],
    config: &CoreConfig,
    mode: SecurityMode,
) -> Result<Zeroizing<Vec<u8>>> {
    mode.validate()?;
    config.validate()?;
    decrypt_aes_gcm_internal(encrypted_data, key)
}

// ============================================================================
// Unverified API (Opt-Out)
// ============================================================================

/// Encrypt data using AES-256-GCM without Zero Trust verification.
///
/// This is an opt-out function for scenarios where Zero Trust verification
/// is not required or not possible. For verified operations, use
/// `encrypt_aes_gcm(data, key, SecurityMode::Verified(&session))`.
///
/// # Key Requirements
///
/// The `key` must be exactly 32 bytes (AES-256). Any other key length
/// returns an error.
///
/// # Errors
///
/// Returns an error if:
/// - The key length is not exactly 32 bytes
/// - Random nonce generation fails
/// - The encryption operation fails
#[inline]
pub fn encrypt_aes_gcm_unverified(data: &[u8], key: &[u8]) -> Result<Vec<u8>> {
    encrypt_aes_gcm(data, key, SecurityMode::Unverified)
}

/// Decrypt data using AES-256-GCM without Zero Trust verification.
///
/// This is an opt-out function for scenarios where Zero Trust verification
/// is not required or not possible. For verified operations, use
/// `decrypt_aes_gcm(encrypted_data, key, SecurityMode::Verified(&session))`.
///
/// # Errors
///
/// Returns an error if:
/// - The encrypted data is shorter than 12 bytes (nonce size)
/// - The key length is less than 32 bytes
/// - The decryption operation fails (e.g., authentication tag mismatch)
#[inline]
pub fn decrypt_aes_gcm_unverified(encrypted_data: &[u8], key: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
    decrypt_aes_gcm(encrypted_data, key, SecurityMode::Unverified)
}

/// Encrypt data using AES-256-GCM with Additional Authenticated Data (AAD).
///
/// AAD is authenticated but not encrypted — it binds context (e.g., a header,
/// key ID, or metadata) to the ciphertext so that decryption fails unless the
/// identical AAD is supplied.
///
/// # Wire Format
///
/// Output: `nonce(12) || ciphertext || tag(16)` (same as without AAD).
///
/// # Errors
///
/// Returns an error if:
/// - The session has expired when using `Verified` mode
/// - The key length is not exactly 32 bytes
/// - Random nonce generation fails
/// - The encryption operation fails
#[inline]
pub fn encrypt_aes_gcm_with_aad(
    data: &[u8],
    key: &[u8],
    aad: &[u8],
    mode: SecurityMode,
) -> Result<Vec<u8>> {
    mode.validate()?;
    encrypt_aes_gcm_with_aad_internal(data, key, aad)
}

/// Decrypt data using AES-256-GCM with Additional Authenticated Data (AAD).
///
/// The same AAD that was used during encryption must be provided; otherwise
/// decryption will fail with `DecryptionFailed`.
///
/// # Errors
///
/// Returns an error if:
/// - The session has expired when using `Verified` mode
/// - The encrypted data is shorter than 12 bytes (nonce size)
/// - The key length is not exactly 32 bytes
/// - The AAD does not match the value used during encryption
/// - The decryption operation fails
#[inline]
pub fn decrypt_aes_gcm_with_aad(
    encrypted_data: &[u8],
    key: &[u8],
    aad: &[u8],
    mode: SecurityMode,
) -> Result<Zeroizing<Vec<u8>>> {
    mode.validate()?;
    decrypt_aes_gcm_with_aad_internal(encrypted_data, key, aad)
}

/// Encrypt data using AES-256-GCM with AAD without Zero Trust verification.
///
/// This is an opt-out function for scenarios where Zero Trust verification
/// is not required or not possible.
///
/// # Errors
///
/// Returns an error if:
/// - The key length is not exactly 32 bytes
/// - Random nonce generation fails
/// - The encryption operation fails
#[inline]
pub fn encrypt_aes_gcm_with_aad_unverified(data: &[u8], key: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
    encrypt_aes_gcm_with_aad(data, key, aad, SecurityMode::Unverified)
}

/// Decrypt data using AES-256-GCM with AAD without Zero Trust verification.
///
/// This is an opt-out function for scenarios where Zero Trust verification
/// is not required or not possible.
///
/// # Errors
///
/// Returns an error if:
/// - The encrypted data is shorter than 12 bytes (nonce size)
/// - The key length is not exactly 32 bytes
/// - The AAD does not match the value used during encryption
/// - The decryption operation fails
#[inline]
pub fn decrypt_aes_gcm_with_aad_unverified(
    encrypted_data: &[u8],
    key: &[u8],
    aad: &[u8],
) -> Result<Zeroizing<Vec<u8>>> {
    decrypt_aes_gcm_with_aad(encrypted_data, key, aad, SecurityMode::Unverified)
}

/// Encrypt data using AES-256-GCM with configuration without Zero Trust verification.
///
/// This is an opt-out function for scenarios where Zero Trust verification
/// is not required or not possible.
///
/// # Key Requirements
///
/// The `key` must be exactly 32 bytes (AES-256). Any other key length
/// returns an error.
///
/// # Errors
///
/// Returns an error if:
/// - The configuration validation fails
/// - The key length is not exactly 32 bytes
/// - Random nonce generation fails
/// - The encryption operation fails
#[inline]
pub fn encrypt_aes_gcm_with_config_unverified(
    data: &[u8],
    key: &[u8],
    config: &CoreConfig,
) -> Result<Vec<u8>> {
    encrypt_aes_gcm_with_config(data, key, config, SecurityMode::Unverified)
}

/// Decrypt data using AES-256-GCM with configuration without Zero Trust verification.
///
/// This is an opt-out function for scenarios where Zero Trust verification
/// is not required or not possible.
///
/// # Errors
///
/// Returns an error if:
/// - The configuration validation fails
/// - The encrypted data is shorter than 12 bytes (nonce size)
/// - The key length is less than 32 bytes
/// - The decryption operation fails (e.g., authentication tag mismatch)
#[inline]
pub fn decrypt_aes_gcm_with_config_unverified(
    encrypted_data: &[u8],
    key: &[u8],
    config: &CoreConfig,
) -> Result<Zeroizing<Vec<u8>>> {
    decrypt_aes_gcm_with_config(encrypted_data, key, config, SecurityMode::Unverified)
}

#[cfg(test)]
#[allow(
    clippy::panic,
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::arithmetic_side_effects,
    clippy::panic_in_result_fn,
    clippy::unnecessary_wraps,
    clippy::redundant_clone,
    clippy::useless_vec,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::clone_on_copy,
    clippy::len_zero,
    clippy::single_match,
    clippy::unnested_or_patterns,
    clippy::default_constructed_unit_structs,
    clippy::redundant_closure_for_method_calls,
    clippy::semicolon_if_nothing_returned,
    clippy::unnecessary_unwrap,
    clippy::redundant_pattern_matching,
    clippy::missing_const_for_thread_local,
    clippy::get_first,
    clippy::float_cmp,
    clippy::needless_borrows_for_generic_args,
    unused_qualifications
)]
mod tests {
    use super::*;
    use crate::unified_api::CoreConfig;

    // Helper to generate a valid AES-256 key (32 bytes)
    fn generate_test_key() -> Vec<u8> {
        vec![0x42; 32]
    }

    // Basic encryption/decryption roundtrip tests
    #[test]
    fn test_aes_gcm_roundtrip_basic_roundtrip() -> Result<()> {
        let key = generate_test_key();
        let plaintext = b"Test message for AES-256-GCM encryption";

        let ciphertext = encrypt_aes_gcm_unverified(plaintext, &key)?;
        let decrypted = decrypt_aes_gcm_unverified(&ciphertext, &key)?;

        assert_eq!(
            decrypted.as_slice(),
            plaintext.as_slice(),
            "Decrypted text should match original plaintext"
        );
        assert_ne!(ciphertext, plaintext, "Ciphertext should differ from plaintext");
        Ok(())
    }

    #[test]
    fn test_aes_gcm_roundtrip_empty_data_roundtrip() -> Result<()> {
        let key = generate_test_key();
        let plaintext = b"";

        let ciphertext = encrypt_aes_gcm_unverified(plaintext, &key)?;
        let decrypted = decrypt_aes_gcm_unverified(&ciphertext, &key)?;

        assert_eq!(
            decrypted.as_slice(),
            plaintext.as_slice(),
            "Empty data should roundtrip correctly"
        );
        Ok(())
    }

    #[test]
    fn test_aes_gcm_roundtrip_large_data_roundtrip() -> Result<()> {
        let key = generate_test_key();
        let plaintext = vec![0xAB; 10000]; // 10KB of data

        let ciphertext = encrypt_aes_gcm_unverified(&plaintext, &key)?;
        let decrypted = decrypt_aes_gcm_unverified(&ciphertext, &key)?;

        assert_eq!(
            decrypted.as_slice(),
            plaintext.as_slice(),
            "Large data should roundtrip correctly"
        );
        Ok(())
    }

    #[test]
    fn test_aes_gcm_roundtrip_binary_data_roundtrip() -> Result<()> {
        let key = generate_test_key();
        let plaintext = vec![0x00, 0xFF, 0x7F, 0x80, 0x01, 0xFE]; // Various byte values

        let ciphertext = encrypt_aes_gcm_unverified(&plaintext, &key)?;
        let decrypted = decrypt_aes_gcm_unverified(&ciphertext, &key)?;

        assert_eq!(
            decrypted.as_slice(),
            plaintext.as_slice(),
            "Binary data should roundtrip correctly"
        );
        Ok(())
    }

    #[test]
    fn test_aes_gcm_roundtrip_with_config_roundtrip() -> Result<()> {
        let key = generate_test_key();
        let plaintext = b"Test with config";
        let config = CoreConfig::default();

        let ciphertext = encrypt_aes_gcm_with_config_unverified(plaintext, &key, &config)?;
        let decrypted = decrypt_aes_gcm_with_config_unverified(&ciphertext, &key, &config)?;

        assert_eq!(decrypted.as_slice(), plaintext.as_slice(), "Roundtrip with config should work");
        Ok(())
    }

    // Ciphertext format and properties tests
    #[test]
    fn test_aes_gcm_ciphertext_includes_nonce_and_tag_at_minimum_size_has_correct_size()
    -> Result<()> {
        let key = generate_test_key();
        let plaintext = b"Test message";

        let ciphertext = encrypt_aes_gcm_unverified(plaintext, &key)?;

        // Ciphertext = 12 bytes nonce + encrypted data + 16 bytes auth tag
        // Minimum size = 12 (nonce) + 0 (empty plaintext) + 16 (tag) = 28 for empty
        // For our plaintext: 12 + plaintext.len() + 16
        let expected_min_size = 12 + plaintext.len() + 16;
        assert!(
            ciphertext.len() >= expected_min_size,
            "Ciphertext should include nonce and auth tag"
        );
        Ok(())
    }

    #[test]
    fn test_aes_gcm_different_encryptions_produce_different_ciphertexts_succeeds() -> Result<()> {
        let key = generate_test_key();
        let plaintext = b"Same plaintext for both encryptions";

        let ciphertext1 = encrypt_aes_gcm_unverified(plaintext, &key)?;
        let ciphertext2 = encrypt_aes_gcm_unverified(plaintext, &key)?;

        // Due to random nonce, ciphertexts should differ even with same plaintext
        assert_ne!(
            ciphertext1, ciphertext2,
            "Different encryptions should produce different ciphertexts due to random nonce"
        );

        // Both should still decrypt to same plaintext
        let decrypted1 = decrypt_aes_gcm_unverified(&ciphertext1, &key)?;
        let decrypted2 = decrypt_aes_gcm_unverified(&ciphertext2, &key)?;
        assert_eq!(decrypted1.as_slice(), plaintext.as_slice());
        assert_eq!(decrypted2.as_slice(), plaintext.as_slice());
        Ok(())
    }

    // Key validation tests
    #[test]
    fn test_aes_gcm_encrypt_with_short_key_fails() {
        let short_key = vec![0x42; 16]; // Only 16 bytes, need 32
        let plaintext = b"Test";

        let result = encrypt_aes_gcm_unverified(plaintext, &short_key);
        assert!(result.is_err(), "Encryption with short key should fail");
        match result.unwrap_err() {
            CoreError::InvalidKeyLength { expected, actual } => {
                assert_eq!(expected, 32);
                assert_eq!(actual, 16);
            }
            other => panic!("Expected InvalidKeyLength error, got: {:?}", other),
        }
    }

    #[test]
    fn test_aes_gcm_decrypt_with_short_key_fails() {
        let key = generate_test_key();
        let plaintext = b"Test";
        let ciphertext =
            encrypt_aes_gcm_unverified(plaintext, &key).expect("encryption should succeed");

        let short_key = vec![0x42; 16];
        let result = decrypt_aes_gcm_unverified(&ciphertext, &short_key);
        assert!(result.is_err(), "Decryption with short key should fail");
    }

    #[test]
    fn test_aes_gcm_encrypt_with_exact_32_byte_key_succeeds() -> Result<()> {
        let key = generate_test_key(); // Exactly 32 bytes
        let plaintext = b"Test";

        let ciphertext = encrypt_aes_gcm_unverified(plaintext, &key)?;
        let decrypted = decrypt_aes_gcm_unverified(&ciphertext, &key)?;
        assert_eq!(decrypted.as_slice(), plaintext.as_slice());
        Ok(())
    }

    #[test]
    fn test_aes_gcm_encrypt_with_longer_key_rejects_fails() {
        let long_key = vec![0x42; 64]; // 64 bytes - should be rejected (not truncated)
        let plaintext = b"Test";

        let result = encrypt_aes_gcm_unverified(plaintext, &long_key);
        assert!(result.is_err(), "Should reject keys longer than 32 bytes");

        if let Err(CoreError::InvalidKeyLength { expected, actual }) = result {
            assert_eq!(expected, 32);
            assert_eq!(actual, 64);
        } else {
            panic!("Expected InvalidKeyLength error");
        }
    }

    // Ciphertext validation tests
    #[test]
    fn test_aes_gcm_decrypt_with_too_short_ciphertext_fails() {
        let key = generate_test_key();
        let too_short = vec![0x42; 10]; // Less than 12 bytes (nonce size)

        let result = decrypt_aes_gcm_unverified(&too_short, &key);
        assert!(result.is_err(), "Decryption with too-short ciphertext should fail");
        match result.unwrap_err() {
            CoreError::InvalidInput(msg) => {
                assert!(msg.contains("too short"), "Error should mention data is too short");
            }
            other => panic!("Expected InvalidInput error, got: {:?}", other),
        }
    }

    #[test]
    fn test_aes_gcm_decrypt_with_tampered_ciphertext_fails() {
        let key = generate_test_key();
        let plaintext = b"Test message";
        let mut ciphertext =
            encrypt_aes_gcm_unverified(plaintext, &key).expect("encryption should succeed");

        // Tamper with the ciphertext (flip a bit in the encrypted portion, not the nonce)
        if ciphertext.len() > 12 {
            ciphertext[13] ^= 0x01;
        }

        let result = decrypt_aes_gcm_unverified(&ciphertext, &key);
        assert!(result.is_err(), "Decryption with tampered ciphertext should fail");
        match result.unwrap_err() {
            CoreError::DecryptionFailed(_) => {} // Expected
            other => panic!("Expected DecryptionFailed error, got: {:?}", other),
        }
    }

    #[test]
    fn test_aes_gcm_decrypt_with_tampered_nonce_fails() {
        let key = generate_test_key();
        let plaintext = b"Test message";
        let mut ciphertext =
            encrypt_aes_gcm_unverified(plaintext, &key).expect("encryption should succeed");

        // Tamper with the nonce (first 12 bytes)
        ciphertext[5] ^= 0x01;

        let result = decrypt_aes_gcm_unverified(&ciphertext, &key);
        assert!(result.is_err(), "Decryption with tampered nonce should fail");
    }

    // Cross-key decryption test
    #[test]
    fn test_aes_gcm_decrypt_with_wrong_key_fails() {
        let key1 = vec![0x42; 32];
        let key2 = vec![0x43; 32]; // Different key
        let plaintext = b"Test message";

        let ciphertext =
            encrypt_aes_gcm_unverified(plaintext, &key1).expect("encryption should succeed");
        let result = decrypt_aes_gcm_unverified(&ciphertext, &key2);

        assert!(result.is_err(), "Decryption with wrong key should fail");
        match result.unwrap_err() {
            CoreError::DecryptionFailed(_) => {} // Expected
            other => panic!("Expected DecryptionFailed error, got: {:?}", other),
        }
    }

    // SecurityMode tests
    #[test]
    fn test_aes_gcm_encrypt_with_unverified_mode_succeeds() -> Result<()> {
        let key = generate_test_key();
        let plaintext = b"Test";

        let ciphertext = encrypt_aes_gcm(plaintext, &key, SecurityMode::Unverified)?;
        let decrypted = decrypt_aes_gcm(&ciphertext, &key, SecurityMode::Unverified)?;
        assert_eq!(decrypted.as_slice(), plaintext.as_slice());
        Ok(())
    }

    #[test]
    fn test_aes_gcm_encrypt_with_config_and_unverified_mode_succeeds() -> Result<()> {
        let key = generate_test_key();
        let plaintext = b"Test";
        let config = CoreConfig::default();

        let ciphertext =
            encrypt_aes_gcm_with_config(plaintext, &key, &config, SecurityMode::Unverified)?;
        let decrypted =
            decrypt_aes_gcm_with_config(&ciphertext, &key, &config, SecurityMode::Unverified)?;
        assert_eq!(decrypted.as_slice(), plaintext.as_slice());
        Ok(())
    }

    // Edge case: multiple roundtrips with same key
    #[test]
    fn test_aes_gcm_multiple_roundtrips_with_same_key_roundtrip() -> Result<()> {
        let key = generate_test_key();
        let messages = vec![
            b"First message".as_ref(),
            b"Second message".as_ref(),
            b"Third message with different length".as_ref(),
        ];

        for message in messages {
            let ciphertext = encrypt_aes_gcm_unverified(message, &key)?;
            let decrypted = decrypt_aes_gcm_unverified(&ciphertext, &key)?;
            assert_eq!(decrypted.as_slice(), message, "Each message should roundtrip correctly");
        }
        Ok(())
    }

    // Verified session tests
    #[test]
    fn test_aes_gcm_roundtrip_verified_session_roundtrip() -> Result<()> {
        let key = generate_test_key();
        let plaintext = b"Verified session roundtrip test";
        let (auth_pk, auth_sk) = crate::unified_api::generate_keypair()?;
        let session = crate::VerifiedSession::establish(auth_pk.as_slice(), auth_sk.as_ref())?;

        let ct = encrypt_aes_gcm(plaintext, &key, SecurityMode::Verified(&session))?;
        let pt = decrypt_aes_gcm(&ct, &key, SecurityMode::Verified(&session))?;
        assert_eq!(pt.as_slice(), plaintext.as_ref());
        Ok(())
    }

    #[test]
    fn test_aes_gcm_with_config_verified_session_succeeds() -> Result<()> {
        let key = generate_test_key();
        let plaintext = b"Config + verified session test";
        let config = CoreConfig::default();
        let (auth_pk, auth_sk) = crate::unified_api::generate_keypair()?;
        let session = crate::VerifiedSession::establish(auth_pk.as_slice(), auth_sk.as_ref())?;

        let ct = encrypt_aes_gcm_with_config(
            plaintext,
            &key,
            &config,
            SecurityMode::Verified(&session),
        )?;
        let pt = decrypt_aes_gcm_with_config(&ct, &key, &config, SecurityMode::Verified(&session))?;
        assert_eq!(pt.as_slice(), plaintext.as_ref());
        Ok(())
    }

    #[test]
    fn test_aes_gcm_encrypt_with_empty_key_fails() {
        let result = encrypt_aes_gcm_unverified(b"test", &[]);
        assert!(result.is_err());
        match result.unwrap_err() {
            CoreError::InvalidKeyLength { expected, actual } => {
                assert_eq!(expected, 32);
                assert_eq!(actual, 0);
            }
            other => panic!("Expected InvalidKeyLength, got: {:?}", other),
        }
    }

    #[test]
    fn test_aes_gcm_decrypt_with_empty_key_fails() {
        let key = generate_test_key();
        let ct = encrypt_aes_gcm_unverified(b"test", &key).unwrap();
        let result = decrypt_aes_gcm_unverified(&ct, &[]);
        assert!(result.is_err());
    }

    #[test]
    fn test_aes_gcm_decrypt_exactly_12_bytes_succeeds() {
        let key = generate_test_key();
        // Exactly 12 bytes = just a nonce, no ciphertext or tag
        let result = decrypt_aes_gcm_unverified(&[0u8; 12], &key);
        assert!(result.is_err(), "12-byte input has no ciphertext body");
    }

    #[test]
    fn test_aes_gcm_internal_encrypt_wrong_key_length_fails() {
        let result = encrypt_aes_gcm_internal(b"test", &[0u8; 31]);
        assert!(result.is_err());
        let result = encrypt_aes_gcm_internal(b"test", &[0u8; 33]);
        assert!(result.is_err());
    }

    #[test]
    fn test_aes_gcm_internal_decrypt_wrong_key_length_fails() {
        let key = generate_test_key();
        let ct = encrypt_aes_gcm_internal(b"test", &key).unwrap();
        let result = decrypt_aes_gcm_internal(&ct, &[0u8; 31]);
        assert!(result.is_err());
        let result = decrypt_aes_gcm_internal(&ct, &[0u8; 33]);
        assert!(result.is_err());
    }

    // ================================================================
    // AES-GCM with AAD tests
    // ================================================================

    #[test]
    fn test_aes_gcm_with_aad_roundtrip() -> Result<()> {
        let key = generate_test_key();
        let plaintext = b"Encrypt me with context binding";
        let aad = b"authenticated-context-v1";

        let ct = encrypt_aes_gcm_with_aad_unverified(plaintext, &key, aad)?;
        let pt = decrypt_aes_gcm_with_aad_unverified(&ct, &key, aad)?;

        assert_eq!(pt.as_slice(), plaintext.as_slice(), "AAD roundtrip should recover plaintext");
        Ok(())
    }

    #[test]
    fn test_aes_gcm_with_aad_wrong_aad_fails() {
        let key = generate_test_key();
        let plaintext = b"Tamper-evident data";
        let aad = b"correct-aad";
        let wrong_aad = b"wrong-aad";

        let ct = encrypt_aes_gcm_with_aad_unverified(plaintext, &key, aad)
            .expect("encryption should succeed");
        let result = decrypt_aes_gcm_with_aad_unverified(&ct, &key, wrong_aad);

        assert!(result.is_err(), "Mismatched AAD must fail decryption");
        match result.unwrap_err() {
            CoreError::DecryptionFailed(_) => {}
            other => panic!("Expected DecryptionFailed, got: {:?}", other),
        }
    }

    #[test]
    fn test_aes_gcm_with_empty_aad_succeeds() -> Result<()> {
        let key = generate_test_key();
        let plaintext = b"Empty AAD test";

        let ct = encrypt_aes_gcm_with_aad_unverified(plaintext, &key, b"")?;
        let pt = decrypt_aes_gcm_with_aad_unverified(&ct, &key, b"")?;

        assert_eq!(pt.as_slice(), plaintext.as_slice(), "Empty AAD should roundtrip correctly");
        Ok(())
    }

    #[test]
    fn test_aes_gcm_with_aad_verified_session_succeeds() -> Result<()> {
        let key = generate_test_key();
        let plaintext = b"Verified AAD test";
        let aad = b"session-bound-context";
        let (auth_pk, auth_sk) = crate::unified_api::generate_keypair()?;
        let session = crate::VerifiedSession::establish(auth_pk.as_slice(), auth_sk.as_ref())?;

        let ct = encrypt_aes_gcm_with_aad(plaintext, &key, aad, SecurityMode::Verified(&session))?;
        let pt = decrypt_aes_gcm_with_aad(&ct, &key, aad, SecurityMode::Verified(&session))?;

        assert_eq!(pt.as_slice(), plaintext.as_ref());
        Ok(())
    }

    #[test]
    fn test_aes_gcm_with_aad_large_aad_succeeds() -> Result<()> {
        let key = generate_test_key();
        let plaintext = b"Large AAD test";
        let aad = vec![0xBB; 1024]; // 1KB of AAD

        let ct = encrypt_aes_gcm_with_aad_unverified(plaintext, &key, &aad)?;
        let pt = decrypt_aes_gcm_with_aad_unverified(&ct, &key, &aad)?;

        assert_eq!(pt.as_slice(), plaintext.as_slice(), "Large AAD should roundtrip correctly");
        Ok(())
    }

    // Performance/size validation
    #[test]
    fn test_aes_gcm_ciphertext_size_overhead_has_correct_size() -> Result<()> {
        let key = generate_test_key();
        let plaintext = b"Test message";

        let ciphertext = encrypt_aes_gcm_unverified(plaintext, &key)?;

        // AES-GCM overhead = 12 bytes (nonce) + 16 bytes (auth tag) = 28 bytes
        let expected_size = plaintext.len() + 28;
        assert_eq!(
            ciphertext.len(),
            expected_size,
            "Ciphertext should have exact overhead of 28 bytes (12 nonce + 16 tag)"
        );
        Ok(())
    }

    // ---- Coverage: config unverified roundtrip ----

    #[test]
    fn test_encrypt_decrypt_with_config_unverified_roundtrip() -> Result<()> {
        let key = generate_test_key();
        let plaintext = b"Config unverified roundtrip test";
        let config = CoreConfig::default();

        let ct = encrypt_aes_gcm_with_config_unverified(plaintext, &key, &config)?;
        let pt = decrypt_aes_gcm_with_config_unverified(&ct, &key, &config)?;

        assert_eq!(pt.as_slice(), plaintext.as_slice());
        Ok(())
    }

    #[test]
    fn test_config_unverified_wrong_key_length_fails() {
        let short_key = vec![0x42; 16]; // 16 bytes instead of 32
        let plaintext = b"Should fail";
        let config = CoreConfig::default();

        let result = encrypt_aes_gcm_with_config_unverified(plaintext, &short_key, &config);
        assert!(result.is_err());
    }

    #[test]
    fn test_config_unverified_decrypt_wrong_key_fails() -> Result<()> {
        let key = generate_test_key();
        let wrong_key = vec![0xFF; 32];
        let plaintext = b"Decrypt with wrong key";
        let config = CoreConfig::default();

        let ct = encrypt_aes_gcm_with_config_unverified(plaintext, &key, &config)?;
        let result = decrypt_aes_gcm_with_config_unverified(&ct, &wrong_key, &config);
        assert!(result.is_err());
        Ok(())
    }

    #[test]
    fn test_config_unverified_decrypt_short_ciphertext_succeeds() {
        let key = generate_test_key();
        let config = CoreConfig::default();
        let short_data = vec![0u8; 5]; // Less than 12 bytes (nonce)

        let result = decrypt_aes_gcm_with_config_unverified(&short_data, &key, &config);
        assert!(result.is_err());
    }

    #[test]
    fn test_config_unverified_empty_plaintext_succeeds() -> Result<()> {
        let key = generate_test_key();
        let config = CoreConfig::default();
        let plaintext = b"";

        let ct = encrypt_aes_gcm_with_config_unverified(plaintext, &key, &config)?;
        let pt = decrypt_aes_gcm_with_config_unverified(&ct, &key, &config)?;
        assert_eq!(pt.as_slice(), plaintext.as_slice());
        Ok(())
    }

    // ---- Coverage: AAD with SecurityMode ----

    #[test]
    fn test_aad_with_security_mode_unverified_succeeds() -> Result<()> {
        let key = generate_test_key();
        let plaintext = b"AAD SecurityMode test";
        let aad = b"authenticated-context";

        let ct = encrypt_aes_gcm_with_aad(plaintext, &key, aad, SecurityMode::Unverified)?;
        let pt = decrypt_aes_gcm_with_aad(&ct, &key, aad, SecurityMode::Unverified)?;
        assert_eq!(pt.as_slice(), plaintext.as_slice());
        Ok(())
    }

    #[test]
    fn test_aad_wrong_aad_decrypt_fails() -> Result<()> {
        let key = generate_test_key();
        let plaintext = b"AAD mismatch test";
        let aad = b"correct-aad";
        let wrong_aad = b"wrong-aad";

        let ct = encrypt_aes_gcm_with_aad_unverified(plaintext, &key, aad)?;
        let result = decrypt_aes_gcm_with_aad_unverified(&ct, &key, wrong_aad);
        assert!(result.is_err());
        Ok(())
    }

    #[test]
    fn test_aad_internal_wrong_key_length_fails() {
        let short_key = vec![0x42; 16];
        let plaintext = b"AAD key length test";
        let aad = b"some-aad";

        let result = encrypt_aes_gcm_with_aad_internal(plaintext, &short_key, aad);
        assert!(result.is_err());
    }

    #[test]
    fn test_aad_internal_decrypt_short_data_succeeds() {
        let key = generate_test_key();
        let aad = b"some-aad";
        let short_data = vec![0u8; 5];

        let result = decrypt_aes_gcm_with_aad_internal(&short_data, &key, aad);
        assert!(result.is_err());
    }

    #[test]
    fn test_aad_internal_decrypt_wrong_key_length_fails() -> Result<()> {
        let key = generate_test_key();
        let short_key = vec![0x42; 16];
        let plaintext = b"test";
        let aad = b"some-aad";

        let ct = encrypt_aes_gcm_with_aad_internal(plaintext, &key, aad)?;
        let result = decrypt_aes_gcm_with_aad_internal(&ct, &short_key, aad);
        assert!(result.is_err());
        Ok(())
    }
}