latticearc 0.7.1

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
//! Hashing, HMAC, and key derivation operations
//!
//! This module provides cryptographic hashing, HMAC, and key derivation functions.
//!
//! ## Zero Trust Enforcement
//!
//! HMAC and key derivation functions use `SecurityMode` to specify verification behavior:
//! - `SecurityMode::Verified(&session)`: Validates session before operation
//! - `SecurityMode::Unverified`: Skips session validation
//!
//! Hash functions are stateless and don't require a security mode.
//!
//! For opt-out scenarios where Zero Trust verification is not required or not possible,
//! use the `_unverified` variants.

use tracing::debug;

use subtle::ConstantTimeEq;

use crate::log_crypto_operation_error;
use crate::primitives::hash::sha3::sha3_256 as hash_sha3_256;
use crate::primitives::mac::hmac::hmac_sha256;
use crate::primitives::resource_limits::validate_key_derivation_count;
use crate::unified_api::CoreConfig;
use crate::unified_api::error::{CoreError, Result};
use crate::unified_api::logging::op;
use crate::unified_api::zero_trust::SecurityMode;

// ============================================================================
// Internal Implementation
// ============================================================================

/// Internal implementation of HKDF key derivation.
///
/// Delegates to `primitives::kdf::hkdf::hkdf()` so all callers benefit from
/// the same zeroization and hardening (audit H1).
fn derive_key_hkdf(password: &[u8], salt: &[u8], length: usize) -> Result<Vec<u8>> {
    let result = crate::primitives::kdf::hkdf::hkdf(
        password,
        Some(salt),
        Some(crate::types::domains::DERIVE_KEY_INFO),
        length,
    )
    .map_err(|e| CoreError::KeyDerivationFailed(format!("HKDF failed: {e}")))?;
    Ok(result.key().to_vec())
}

/// Internal implementation of HKDF key derivation with caller-supplied info string.
///
/// Delegates to `primitives::kdf::hkdf::hkdf()` so all callers benefit from
/// the same zeroization and hardening (audit H1).
fn derive_key_hkdf_with_info(
    password: &[u8],
    salt: &[u8],
    length: usize,
    info: &[u8],
) -> Result<Vec<u8>> {
    let result = crate::primitives::kdf::hkdf::hkdf(password, Some(salt), Some(info), length)
        .map_err(|e| CoreError::KeyDerivationFailed(format!("HKDF failed: {e}")))?;
    Ok(result.key().to_vec())
}

/// Internal implementation of key derivation with caller-supplied info string.
fn derive_key_with_info_internal(
    password: &[u8],
    salt: &[u8],
    length: usize,
    info: &[u8],
) -> Result<Vec<u8>> {
    crate::log_crypto_operation_start!(
        "key_derivation_info",
        algorithm = "HKDF-SHA256",
        output_len = length,
        info_len = info.len()
    );

    validate_key_derivation_count(1).map_err(|e| {
        log_crypto_operation_error!(op::KEY_DERIVATION_INFO, e);
        CoreError::ResourceExceeded(e.to_string())
    })?;

    if salt.is_empty() {
        let err = CoreError::InvalidInput("Salt cannot be empty".to_string());
        log_crypto_operation_error!(op::KEY_DERIVATION_INFO, err);
        return Err(err);
    }

    if length == 0 {
        let err = CoreError::InvalidInput("Length cannot be zero".to_string());
        log_crypto_operation_error!(op::KEY_DERIVATION_INFO, err);
        return Err(err);
    }

    if info.is_empty() {
        let err = CoreError::InvalidInput("Info string cannot be empty".to_string());
        log_crypto_operation_error!(op::KEY_DERIVATION_INFO, err);
        return Err(err);
    }

    let result = derive_key_hkdf_with_info(password, salt, length, info);

    match &result {
        Ok(_) => {
            crate::log_crypto_operation_complete!(
                "key_derivation_info",
                algorithm = "HKDF-SHA256",
                output_len = length
            );
            debug!(
                algorithm = "HKDF-SHA256",
                output_len = length,
                info_len = info.len(),
                "Key derivation with custom info completed"
            );
        }
        Err(e) => {
            log_crypto_operation_error!(op::KEY_DERIVATION_INFO, e);
        }
    }

    result
}

/// Internal implementation of key derivation.
fn derive_key_internal(password: &[u8], salt: &[u8], length: usize) -> Result<Vec<u8>> {
    crate::log_crypto_operation_start!(
        "key_derivation",
        algorithm = "HKDF-SHA256",
        output_len = length
    );

    validate_key_derivation_count(1).map_err(|e| {
        log_crypto_operation_error!(op::KEY_DERIVATION, e);
        CoreError::ResourceExceeded(e.to_string())
    })?;

    if salt.is_empty() {
        let err = CoreError::InvalidInput("Salt cannot be empty".to_string());
        log_crypto_operation_error!(op::KEY_DERIVATION, err);
        return Err(err);
    }

    if length == 0 {
        let err = CoreError::InvalidInput("Length cannot be zero".to_string());
        log_crypto_operation_error!(op::KEY_DERIVATION, err);
        return Err(err);
    }

    let result = derive_key_hkdf(password, salt, length);

    match &result {
        Ok(_) => {
            crate::log_crypto_operation_complete!(
                "key_derivation",
                algorithm = "HKDF-SHA256",
                output_len = length
            );
            debug!(algorithm = "HKDF-SHA256", output_len = length, "Key derivation completed");
        }
        Err(e) => {
            log_crypto_operation_error!(op::KEY_DERIVATION, e);
        }
    }

    result
}

/// Internal implementation of HMAC.
fn hmac_internal(key: &[u8], data: &[u8]) -> Result<Vec<u8>> {
    crate::log_crypto_operation_start!(op::HMAC, algorithm = "HMAC-SHA256", data_len = data.len());

    if key.is_empty() {
        let err = CoreError::InvalidInput("HMAC key must not be empty".to_string());
        log_crypto_operation_error!(op::HMAC, err);
        return Err(err);
    }

    // Delegate to primitives::mac::hmac (backed by aws-lc-rs HMAC-SHA256).
    let tag = hmac_sha256(key, data).map_err(|e| {
        let err = CoreError::InvalidInput(format!("HMAC computation failed: {e}"));
        log_crypto_operation_error!(op::HMAC, err);
        err
    })?;
    let result = tag.to_vec();
    crate::log_crypto_operation_complete!(
        "hmac",
        algorithm = "HMAC-SHA256",
        tag_len = result.len()
    );
    debug!(algorithm = "HMAC-SHA256", data_len = data.len(), "HMAC computed");

    Ok(result)
}

/// Internal implementation of HMAC verification.
fn hmac_verify_internal(key: &[u8], data: &[u8], tag: &[u8]) -> Result<bool> {
    crate::log_crypto_operation_start!(
        "hmac_verify",
        algorithm = "HMAC-SHA256",
        data_len = data.len()
    );

    if key.is_empty() {
        let err = CoreError::InvalidInput("HMAC key must not be empty".to_string());
        log_crypto_operation_error!(op::HMAC_VERIFY, err);
        return Err(err);
    }

    if tag.len() != 32 {
        let err = CoreError::InvalidInput(format!("HMAC tag must be 32 bytes, got {}", tag.len()));
        log_crypto_operation_error!(op::HMAC_VERIFY, err);
        return Err(err);
    }

    let expected = hmac_internal(key, data)?;

    let mut tag_bytes = [0u8; 32];
    tag_bytes.copy_from_slice(tag);
    let mut expected_bytes = [0u8; 32];
    expected_bytes.copy_from_slice(&expected);

    let valid: bool = tag_bytes.ct_eq(&expected_bytes).into();

    crate::log_crypto_operation_complete!(
        op::HMAC_VERIFY,
        algorithm = "HMAC-SHA256",
        valid = valid
    );
    debug!(algorithm = "HMAC-SHA256", valid = valid, "HMAC verification completed");

    Ok(valid)
}

// ============================================================================
// Hash Functions (Stateless - No Session Required)
// ============================================================================

/// Hash data using SHA3-256.
///
/// This function is infallible and returns the computed hash directly.
/// Hash operations are stateless and don't require a verified session.
#[inline]
#[must_use]
pub fn hash_data(data: &[u8]) -> [u8; 32] {
    debug!(algorithm = "SHA3-256", data_len = data.len(), "Hashing data");
    let result = hash_sha3_256(data);
    debug!(algorithm = "SHA3-256", "Hash completed");
    result
}

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

/// Derive a key from high-entropy input keying material using HKDF-SHA256
/// (RFC 5869 / SP 800-56C).
///
/// # Do NOT use this for passwords
///
/// HKDF is designed for *high-entropy* inputs: Diffie-Hellman shared secrets,
/// raw random bytes from a CSPRNG, output of another KEM, and so on. It
/// performs **no work factor** and provides **zero brute-force resistance**
/// against low-entropy inputs. Passing a user passphrase here gives an
/// attacker who steals the ciphertext a line-rate password oracle.
///
/// For password-based key derivation, use
/// [`crate::primitives::kdf::pbkdf2::pbkdf2`] with at least 600,000 iterations
/// of HMAC-SHA256 (OWASP 2023 recommendation) and a **fresh per-user random
/// salt** stored alongside the ciphertext. A complete worked example lives in
/// `examples/complete_secure_workflow.rs`.
///
/// The `ikm` parameter is named as such to make this contract explicit — it
/// is *input keying material*, not a password.
///
/// # Security modes
///
/// - `SecurityMode::Verified(&session)`: Validates the session before derivation
/// - `SecurityMode::Unverified`: Skips session validation
///
/// # Example (HKDF with a DH shared secret — correct use)
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use latticearc::unified_api::{derive_key, SecurityMode};
/// // `shared_secret` is e.g. the output of X25519 or ML-KEM — high entropy.
/// # let shared_secret = [0u8; 32];
/// # let salt = [0u8; 16]; // per-session random salt, optional
/// let key = derive_key(&shared_secret, &salt, 32, SecurityMode::Unverified)?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - The mode is `Verified` and the session has expired (`CoreError::SessionExpired`)
/// - The resource limit for key derivation operations is exceeded
/// - The salt is empty
/// - The requested length is zero
/// - The HKDF expansion operation fails
pub fn derive_key(ikm: &[u8], salt: &[u8], length: usize, mode: SecurityMode) -> Result<Vec<u8>> {
    mode.validate()?;
    derive_key_internal(ikm, salt, length)
}

/// Compute HMAC-SHA256 of data.
///
/// Uses `SecurityMode` to specify verification behavior:
/// - `SecurityMode::Verified(&session)`: Validates session before HMAC computation
/// - `SecurityMode::Unverified`: Skips session validation
///
/// # Example
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use latticearc::unified_api::{hmac, SecurityMode, VerifiedSession};
/// # let data = b"data";
/// # let key = b"key";
/// # let pk = [0u8; 32];
/// # let sk = [0u8; 32];
///
/// // With Zero Trust (recommended)
/// let session = VerifiedSession::establish(&pk, &sk)?;
/// let tag = hmac(data, key, SecurityMode::Verified(&session))?;
///
/// // Without verification (opt-out)
/// let tag = hmac(data, key, SecurityMode::Unverified)?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - The mode is `Verified` and the session has expired (`CoreError::SessionExpired`)
/// - The HMAC key is empty
#[inline]
pub fn hmac(data: &[u8], key: &[u8], mode: SecurityMode) -> Result<Vec<u8>> {
    mode.validate()?;
    hmac_internal(key, data)
}

/// Check HMAC-SHA256 tag in constant time.
///
/// Uses `SecurityMode` to specify verification behavior:
/// - `SecurityMode::Verified(&session)`: Validates session before HMAC verification
/// - `SecurityMode::Unverified`: Skips session validation
///
/// The function name uses "check" rather than "verify" to avoid confusion with
/// the Zero Trust `_unverified` suffix pattern.
///
/// # Example
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use latticearc::unified_api::{hmac_check, SecurityMode, VerifiedSession};
/// # let data = b"data";
/// # let key = b"key";
/// # let tag = &[0u8; 32];
/// # let pk = [0u8; 32];
/// # let sk = [0u8; 32];
///
/// // With Zero Trust (recommended)
/// let session = VerifiedSession::establish(&pk, &sk)?;
/// let is_valid = hmac_check(data, key, tag, SecurityMode::Verified(&session))?;
///
/// // Without verification (opt-out)
/// let is_valid = hmac_check(data, key, tag, SecurityMode::Unverified)?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - The mode is `Verified` and the session has expired (`CoreError::SessionExpired`)
/// - The HMAC key is empty
/// - The tag is not exactly 32 bytes
#[inline]
pub fn hmac_check(data: &[u8], key: &[u8], tag: &[u8], mode: SecurityMode) -> Result<bool> {
    mode.validate()?;
    hmac_verify_internal(key, data, tag)
}

/// Derive a key from a password and salt using HKDF with custom configuration.
///
/// # Errors
///
/// Returns an error if:
/// - The mode is `Verified` and the session has expired (`CoreError::SessionExpired`)
/// - The configuration validation fails
/// - The salt is empty or length is zero
/// - The HKDF expansion operation fails
pub fn derive_key_with_config(
    password: &[u8],
    salt: &[u8],
    length: usize,
    config: &CoreConfig,
    mode: SecurityMode,
) -> Result<Vec<u8>> {
    mode.validate()?;
    config.validate()?;
    derive_key_internal(password, salt, length)
}

/// Compute HMAC-SHA256 of data with custom configuration.
///
/// # Errors
///
/// Returns an error if:
/// - The mode is `Verified` and the session has expired (`CoreError::SessionExpired`)
/// - The configuration validation fails
/// - The HMAC key is empty
#[inline]
pub fn hmac_with_config(
    data: &[u8],
    key: &[u8],
    config: &CoreConfig,
    mode: SecurityMode,
) -> Result<Vec<u8>> {
    mode.validate()?;
    config.validate()?;
    hmac_internal(key, data)
}

/// Check HMAC-SHA256 tag in constant time with custom configuration.
///
/// # Errors
///
/// Returns an error if:
/// - The mode is `Verified` and the session has expired (`CoreError::SessionExpired`)
/// - The configuration validation fails
/// - The HMAC key is empty or tag is invalid
#[inline]
pub fn hmac_check_with_config(
    data: &[u8],
    key: &[u8],
    tag: &[u8],
    config: &CoreConfig,
    mode: SecurityMode,
) -> Result<bool> {
    mode.validate()?;
    config.validate()?;
    hmac_verify_internal(key, data, tag)
}

// ============================================================================
// Unverified API (Opt-Out Functions)
// ============================================================================
// These functions are for scenarios where Zero Trust verification is not required or not possible.

/// Derive a key using HKDF-SHA256 with a caller-supplied info string for domain separation.
///
/// This function is identical to [`derive_key`] except that the HKDF expansion
/// step uses the caller-provided `info` parameter instead of the library default.
/// Different `info` values produce different keys from the same input keying
/// material, enabling safe domain separation across multiple derivation contexts.
///
/// # Errors
///
/// Returns an error if:
/// - The mode is `Verified` and the session has expired (`CoreError::SessionExpired`)
/// - The resource limit for key derivation operations is exceeded
/// - The salt is empty
/// - The requested length is zero
/// - The info string is empty
/// - The HKDF expansion operation fails
pub fn derive_key_with_info(
    password: &[u8],
    salt: &[u8],
    length: usize,
    info: &[u8],
    mode: SecurityMode,
) -> Result<Vec<u8>> {
    mode.validate()?;
    derive_key_with_info_internal(password, salt, length, info)
}

// ============================================================================
// Unverified API (Opt-Out) — see `convenience::mod` docs for the shared
// security guidance on when to use `_unverified` variants.
// ============================================================================

/// Derive a key using HKDF-SHA256 with a caller-supplied info string 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 resource limit for key derivation operations is exceeded
/// - The salt is empty
/// - The requested length is zero
/// - The info string is empty
/// - The HKDF expansion operation fails
pub fn derive_key_with_info_unverified(
    password: &[u8],
    salt: &[u8],
    length: usize,
    info: &[u8],
) -> Result<Vec<u8>> {
    derive_key_with_info(password, salt, length, info, SecurityMode::Unverified)
}

/// Derive a key from a password and salt using HKDF 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 resource limit for key derivation operations is exceeded
/// - The salt is empty
/// - The requested length is zero
/// - The HKDF expansion operation fails
pub fn derive_key_unverified(password: &[u8], salt: &[u8], length: usize) -> Result<Vec<u8>> {
    derive_key(password, salt, length, SecurityMode::Unverified)
}

/// Compute HMAC-SHA256 of data 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 HMAC key is empty
#[inline]
pub fn hmac_unverified(data: &[u8], key: &[u8]) -> Result<Vec<u8>> {
    hmac(data, key, SecurityMode::Unverified)
}

/// Check HMAC-SHA256 tag in constant time 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 HMAC key is empty
/// - The tag is not exactly 32 bytes
#[inline]
pub fn hmac_check_unverified(data: &[u8], key: &[u8], tag: &[u8]) -> Result<bool> {
    hmac_check(data, key, tag, SecurityMode::Unverified)
}

/// Derive a key 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 salt is empty or length is zero
/// - The HKDF expansion operation fails
pub fn derive_key_with_config_unverified(
    password: &[u8],
    salt: &[u8],
    length: usize,
    config: &CoreConfig,
) -> Result<Vec<u8>> {
    derive_key_with_config(password, salt, length, config, SecurityMode::Unverified)
}

/// Compute HMAC-SHA256 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 HMAC key is empty
#[inline]
pub fn hmac_with_config_unverified(
    key: &[u8],
    data: &[u8],
    config: &CoreConfig,
) -> Result<Vec<u8>> {
    hmac_with_config(data, key, config, SecurityMode::Unverified)
}

/// Check HMAC-SHA256 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 HMAC key is empty or tag is invalid
#[inline]
pub fn hmac_check_with_config_unverified(
    key: &[u8],
    data: &[u8],
    tag: &[u8],
    config: &CoreConfig,
) -> Result<bool> {
    hmac_check_with_config(data, key, tag, 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::{SecurityMode, VerifiedSession, generate_keypair};

    // hash_data tests
    #[test]
    fn test_hash_data_deterministic_returns_same_hash_is_deterministic() {
        let data = b"Test data for hashing";
        let hash1 = hash_data(data);
        let hash2 = hash_data(data);
        assert_eq!(hash1, hash2, "Hash should be deterministic");
        assert_eq!(hash1.len(), 32, "SHA-256 hash should be 32 bytes");
    }

    #[test]
    fn test_hash_data_different_inputs_produce_distinct_hashes_are_unique() {
        let data1 = b"First message";
        let data2 = b"Second message";
        let hash1 = hash_data(data1);
        let hash2 = hash_data(data2);
        assert_ne!(hash1, hash2, "Different inputs should produce different hashes");
    }

    #[test]
    fn test_hash_data_empty_input_returns_32_byte_hash_fails() {
        let data = b"";
        let hash = hash_data(data);
        assert_eq!(hash.len(), 32, "Empty input should still produce 32-byte hash");
    }

    #[test]
    fn test_hash_data_large_input_returns_32_byte_hash_succeeds() {
        let data = vec![0xAB; 100000];
        let hash = hash_data(&data);
        assert_eq!(hash.len(), 32, "Large input should produce 32-byte hash");
    }

    // derive_key tests (unverified API)
    #[test]
    fn test_derive_key_unverified_basic_returns_correct_length_has_correct_size() -> Result<()> {
        let password = b"strong_password";
        let salt = b"random_salt_1234";
        let key = derive_key_unverified(password, salt, 32)?;
        assert_eq!(key.len(), 32);
        Ok(())
    }

    #[test]
    fn test_derive_key_unverified_deterministic_returns_same_key_is_deterministic() -> Result<()> {
        let password = b"test_password";
        let salt = b"test_salt";
        let key1 = derive_key_unverified(password, salt, 32)?;
        let key2 = derive_key_unverified(password, salt, 32)?;
        assert_eq!(key1, key2, "Key derivation should be deterministic");
        Ok(())
    }

    #[test]
    fn test_derive_key_unverified_different_passwords_produce_distinct_keys_are_unique()
    -> Result<()> {
        let salt = b"same_salt";
        let key1 = derive_key_unverified(b"password1", salt, 32)?;
        let key2 = derive_key_unverified(b"password2", salt, 32)?;
        assert_ne!(key1, key2, "Different passwords should produce different keys");
        Ok(())
    }

    #[test]
    fn test_derive_key_unverified_different_salts_produce_distinct_keys_are_unique() -> Result<()> {
        let password = b"same_password";
        let key1 = derive_key_unverified(password, b"salt1", 32)?;
        let key2 = derive_key_unverified(password, b"salt2", 32)?;
        assert_ne!(key1, key2, "Different salts should produce different keys");
        Ok(())
    }

    #[test]
    fn test_derive_key_unverified_different_lengths_return_correct_sizes_has_correct_size()
    -> Result<()> {
        let password = b"password";
        let salt = b"salt";
        let key16 = derive_key_unverified(password, salt, 16)?;
        let key32 = derive_key_unverified(password, salt, 32)?;
        let key64 = derive_key_unverified(password, salt, 64)?;
        assert_eq!(key16.len(), 16);
        assert_eq!(key32.len(), 32);
        assert_eq!(key64.len(), 64);
        Ok(())
    }

    // derive_key with config tests
    #[test]
    fn test_derive_key_with_config_unverified_succeeds() -> Result<()> {
        let password = b"password";
        let salt = b"salt";
        let config = CoreConfig::default();
        let key = derive_key_with_config_unverified(password, salt, 32, &config)?;
        assert_eq!(key.len(), 32);
        Ok(())
    }

    // derive_key verified API tests
    #[test]
    fn test_derive_key_verified_mode_succeeds() -> Result<()> {
        let password = b"secure_password";
        let salt = b"secure_salt";
        let (auth_pk, auth_sk) = generate_keypair()?;
        let session = VerifiedSession::establish(auth_pk.as_slice(), auth_sk.as_ref())?;

        let key = derive_key(password, salt, 32, SecurityMode::Verified(&session))?;
        assert_eq!(key.len(), 32);
        Ok(())
    }

    #[test]
    fn test_derive_key_unverified_mode_succeeds() -> Result<()> {
        let password = b"password";
        let salt = b"salt";
        let key = derive_key(password, salt, 32, SecurityMode::Unverified)?;
        assert_eq!(key.len(), 32);
        Ok(())
    }

    // HMAC tests (unverified API)
    #[test]
    fn test_hmac_unverified_basic_returns_32_byte_tag_succeeds() -> Result<()> {
        let key = b"secret_key_1234567890";
        let data = b"Message to authenticate";
        let tag = hmac_unverified(data, key)?;
        assert!(!tag.is_empty());
        assert_eq!(tag.len(), 32, "HMAC-SHA256 should produce 32-byte tag");
        Ok(())
    }

    #[test]
    fn test_hmac_unverified_deterministic_returns_same_tag_is_deterministic() -> Result<()> {
        let key = b"key";
        let data = b"data";
        let tag1 = hmac_unverified(data, key)?;
        let tag2 = hmac_unverified(data, key)?;
        assert_eq!(tag1, tag2, "HMAC should be deterministic");
        Ok(())
    }

    #[test]
    fn test_hmac_check_unverified_valid_succeeds() -> Result<()> {
        let key = b"authentication_key";
        let data = b"Important message";
        let tag = hmac_unverified(data, key)?;
        let is_valid = hmac_check_unverified(data, key, &tag)?;
        assert!(is_valid, "Valid HMAC should verify successfully");
        Ok(())
    }

    #[test]
    fn test_hmac_check_unverified_wrong_key_returns_false_fails() -> Result<()> {
        let key1 = b"key1";
        let key2 = b"key2";
        let data = b"data";
        let tag = hmac_unverified(data, key1)?;
        let is_valid = hmac_check_unverified(data, key2, &tag)?;
        assert!(!is_valid, "Wrong key should fail verification");
        Ok(())
    }

    #[test]
    fn test_hmac_check_unverified_wrong_data_returns_false_fails() -> Result<()> {
        let key = b"key";
        let data1 = b"original data";
        let data2 = b"modified data";
        let tag = hmac_unverified(data1, key)?;
        let is_valid = hmac_check_unverified(data2, key, &tag)?;
        assert!(!is_valid, "Wrong data should fail verification");
        Ok(())
    }

    #[test]
    fn test_hmac_check_unverified_invalid_tag_returns_false_fails() -> Result<()> {
        let key = b"key";
        let data = b"data";
        let invalid_tag = vec![0u8; 32];
        let is_valid = hmac_check_unverified(data, key, &invalid_tag)?;
        assert!(!is_valid, "Invalid tag should fail verification");
        Ok(())
    }

    // HMAC with config tests
    #[test]
    fn test_hmac_with_config_unverified_succeeds() -> Result<()> {
        let key = b"key";
        let data = b"data";
        let config = CoreConfig::default();
        let tag = hmac_with_config_unverified(data, key, &config)?;
        let is_valid = hmac_check_with_config_unverified(data, key, &tag, &config)?;
        assert!(is_valid);
        Ok(())
    }

    // HMAC verified API tests
    #[test]
    fn test_hmac_verified_mode_succeeds() -> Result<()> {
        let key = b"secret_key";
        let data = b"authenticated message";
        let (auth_pk, auth_sk) = generate_keypair()?;
        let session = VerifiedSession::establish(auth_pk.as_slice(), auth_sk.as_ref())?;

        let tag = hmac(data, key, SecurityMode::Verified(&session))?;
        let is_valid = hmac_check(data, key, &tag, SecurityMode::Verified(&session))?;
        assert!(is_valid);
        Ok(())
    }

    #[test]
    fn test_hmac_unverified_mode_succeeds() -> Result<()> {
        let key = b"key";
        let data = b"data";
        let tag = hmac(data, key, SecurityMode::Unverified)?;
        let is_valid = hmac_check(data, key, &tag, SecurityMode::Unverified)?;
        assert!(is_valid);
        Ok(())
    }

    #[test]
    fn test_hmac_with_config_verified_succeeds() -> Result<()> {
        let key = b"key";
        let data = b"data";
        let config = CoreConfig::default();
        let (auth_pk, auth_sk) = generate_keypair()?;
        let session = VerifiedSession::establish(auth_pk.as_slice(), auth_sk.as_ref())?;

        let tag = hmac_with_config(data, key, &config, SecurityMode::Verified(&session))?;
        let is_valid =
            hmac_check_with_config(data, key, &tag, &config, SecurityMode::Verified(&session))?;
        assert!(is_valid);
        Ok(())
    }

    // Error path tests
    #[test]
    fn test_derive_key_empty_salt_fails() {
        let result = derive_key_unverified(b"password", b"", 32);
        assert!(result.is_err(), "Empty salt should fail");
        match result.unwrap_err() {
            CoreError::InvalidInput(msg) => assert!(msg.contains("Salt")),
            other => panic!("Expected InvalidInput, got: {:?}", other),
        }
    }

    #[test]
    fn test_derive_key_zero_length_fails() {
        let result = derive_key_unverified(b"password", b"salt", 0);
        assert!(result.is_err(), "Zero length should fail");
        match result.unwrap_err() {
            CoreError::InvalidInput(msg) => assert!(msg.contains("Length")),
            other => panic!("Expected InvalidInput, got: {:?}", other),
        }
    }

    #[test]
    fn test_hmac_empty_key_fails() {
        let result = hmac_unverified(b"data", &[]);
        assert!(result.is_err(), "Empty HMAC key should fail");
        match result.unwrap_err() {
            CoreError::InvalidInput(msg) => assert!(msg.contains("key")),
            other => panic!("Expected InvalidInput, got: {:?}", other),
        }
    }

    #[test]
    fn test_hmac_check_wrong_tag_length_fails() {
        let result = hmac_check_unverified(b"data", b"key", &[0u8; 16]);
        assert!(result.is_err(), "Wrong tag length should fail");
        match result.unwrap_err() {
            CoreError::InvalidInput(msg) => assert!(msg.contains("32 bytes")),
            other => panic!("Expected InvalidInput, got: {:?}", other),
        }
    }

    #[test]
    fn test_hmac_check_empty_key_fails() {
        let result = hmac_check_unverified(b"data", &[], &[0u8; 32]);
        assert!(result.is_err(), "Empty key for HMAC check should fail");
    }

    // Derive key with config + verified session
    #[test]
    fn test_derive_key_with_config_verified_succeeds() -> Result<()> {
        let password = b"password";
        let salt = b"salt";
        let config = CoreConfig::default();
        let (auth_pk, auth_sk) = generate_keypair()?;
        let session = VerifiedSession::establish(auth_pk.as_slice(), auth_sk.as_ref())?;

        let key =
            derive_key_with_config(password, salt, 32, &config, SecurityMode::Verified(&session))?;
        assert_eq!(key.len(), 32);
        Ok(())
    }

    // HMAC check with config + unverified (covers _with_config_unverified for hmac_check)
    #[test]
    fn test_hmac_check_with_config_unverified_roundtrip() -> Result<()> {
        let key = b"test_key";
        let data = b"important data";
        let config = CoreConfig::default();

        let tag = hmac_with_config_unverified(data, key, &config)?;
        let valid = hmac_check_with_config_unverified(data, key, &tag, &config)?;
        assert!(valid);

        // Wrong data should fail
        let valid = hmac_check_with_config_unverified(b"wrong data", key, &tag, &config)?;
        assert!(!valid);
        Ok(())
    }

    // ================================================================
    // derive_key_with_info tests
    // ================================================================

    #[test]
    fn test_derive_key_with_info_basic_succeeds() -> Result<()> {
        let password = b"ikm-material";
        let salt = b"random-salt";
        let info = b"my-application-context";
        let key = derive_key_with_info_unverified(password, salt, 32, info)?;
        assert_eq!(key.len(), 32);
        Ok(())
    }

    #[test]
    fn test_derive_key_with_info_deterministic() -> Result<()> {
        let password = b"test-ikm";
        let salt = b"test-salt";
        let info = b"test-info";
        let key1 = derive_key_with_info_unverified(password, salt, 32, info)?;
        let key2 = derive_key_with_info_unverified(password, salt, 32, info)?;
        assert_eq!(key1, key2, "Same inputs must produce same key");
        Ok(())
    }

    #[test]
    fn test_derive_key_with_info_different_info_succeeds() -> Result<()> {
        let password = b"same-ikm";
        let salt = b"same-salt";
        let key_a = derive_key_with_info_unverified(password, salt, 32, b"context-a")?;
        let key_b = derive_key_with_info_unverified(password, salt, 32, b"context-b")?;
        assert_ne!(key_a, key_b, "Different info strings must produce different keys");
        Ok(())
    }

    #[test]
    fn test_derive_key_with_info_vs_standard_succeeds() -> Result<()> {
        let password = b"shared-ikm";
        let salt = b"shared-salt";
        // Using the library's default info string should match derive_key
        let via_info = derive_key_with_info_unverified(
            password,
            salt,
            32,
            crate::types::domains::DERIVE_KEY_INFO,
        )?;
        let via_standard = derive_key_unverified(password, salt, 32)?;
        assert_eq!(via_info, via_standard, "DERIVE_KEY_INFO must match derive_key output");
        Ok(())
    }

    #[test]
    fn test_derive_key_with_info_empty_info_fails() {
        let result = derive_key_with_info_unverified(b"ikm", b"salt", 32, b"");
        assert!(result.is_err(), "Empty info string should fail");
        match result.unwrap_err() {
            CoreError::InvalidInput(msg) => assert!(msg.contains("Info")),
            other => panic!("Expected InvalidInput, got: {:?}", other),
        }
    }

    #[test]
    fn test_derive_key_with_info_verified_session_succeeds() -> Result<()> {
        let password = b"ikm";
        let salt = b"salt";
        let info = b"verified-context";
        let (auth_pk, auth_sk) = generate_keypair()?;
        let session = VerifiedSession::establish(auth_pk.as_slice(), auth_sk.as_ref())?;

        let key = derive_key_with_info(password, salt, 32, info, SecurityMode::Verified(&session))?;
        assert_eq!(key.len(), 32);
        Ok(())
    }

    // Hash parallel path (data > 65536 bytes)
    #[test]
    fn test_hash_data_parallel_path_is_deterministic() {
        let data = vec![0xAB; 70000]; // > 65536 to trigger parallel path
        let hash1 = hash_data(&data);
        let hash2 = hash_data(&data);
        assert_eq!(hash1, hash2, "Parallel hash should be deterministic");
        assert_eq!(hash1.len(), 32);
    }

    // Edge cases
    #[test]
    fn test_hmac_empty_data_succeeds() -> Result<()> {
        let key = b"key";
        let data = b"";
        let tag = hmac_unverified(data, key)?;
        let is_valid = hmac_check_unverified(data, key, &tag)?;
        assert!(is_valid);
        Ok(())
    }

    #[test]
    fn test_hmac_large_data_succeeds() -> Result<()> {
        let key = b"key";
        let data = vec![0x42; 100000];
        let tag = hmac_unverified(&data, key)?;
        let is_valid = hmac_check_unverified(&data, key, &tag)?;
        assert!(is_valid);
        Ok(())
    }

    #[test]
    fn test_hmac_different_key_lengths_produce_distinct_tags_has_correct_size() -> Result<()> {
        let data = b"test data";
        let key16 = b"1234567890123456"; // 16 bytes
        let key32 = b"12345678901234567890123456789012"; // 32 bytes

        let tag16 = hmac_unverified(data, key16)?;
        let tag32 = hmac_unverified(data, key32)?;

        assert!(hmac_check_unverified(data, key16, &tag16)?);
        assert!(hmac_check_unverified(data, key32, &tag32)?);
        assert_ne!(tag16, tag32, "Different keys should produce different tags");
        Ok(())
    }
}