synta-certificate 0.2.6

X.509 certificate structures for synta ASN.1 library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
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
//! NSS-backed [`crate::crypto::DataHasher`] and [`crate::crypto::HmacProvider`]
//! implementations.
//!
//! - Hashing delegates to `PK11_HashBuf` (shared with [`NssKeyIdHasher`]).
//! - HMAC uses the PKCS#11 symmetric-key mechanism:
//!   `PK11_ImportSymKey` → `PK11_CreateContextBySymKey` → `PK11_DigestOp` →
//!   `PK11_DigestFinal`.
//!
//! Both accept the string algorithm names used throughout this crate:
//! `"sha1"`, `"sha256"`, `"sha384"`, `"sha512"`.
//!
//! [`NssKeyIdHasher`]: super::NssKeyIdHasher

use nss_sys::nspr::PR_TRUE;
use nss_sys::{SECItemStr, SECItemType};

use super::ffi::{
    CKMechanismType, CkAesGcmParams, PK11ContextStr, PK11_CipherOp, PK11_CreateContextBySymKey,
    PK11_CreateDigestContext, PK11_DestroyContext, PK11_DigestBegin, PK11_DigestFinal,
    PK11_DigestOp, PK11_FreeSlot, PK11_FreeSymKey, PK11_GenerateRandom, PK11_GetInternalSlot,
    PK11_ImportSymKey, CKA_DECRYPT, CKA_ENCRYPT, CKM_AES_CBC, CKM_AES_CBC_PAD, CKM_AES_GCM,
    CKM_DES3_CBC, CKM_DES3_CBC_PAD, CKM_MD5_HMAC, CKM_SHA224_HMAC, CKM_SHA256_HMAC,
    CKM_SHA384_HMAC, CKM_SHA512_HMAC, CKM_SHA_1_HMAC, PK11_ORIGIN_UNWRAP,
};
use super::{alg_name_to_hash_tag, ensure_nss_init};
use crate::crypto::{
    constant_time_eq, BlockCipherProvider, DataHasher, ErasedDataHasher, ErasedHmacProvider,
    ErasedStreamingHmacProvider, HmacProvider, HmacState, Pbkdf2Provider, PrivateKeyError,
    SecureRandom, StreamingHmacProvider,
};

// ── NssHashState ──────────────────────────────────────────────────────────────

/// Live streaming hash computation backed by a PKCS#11 digest context.
struct NssHashState {
    /// The PKCS#11 digest context; `None` after `finalize_boxed` takes it.
    ctx: Option<std::ptr::NonNull<PK11ContextStr>>,
    output_len: usize,
}

// SAFETY: NSS PKCS#11 contexts are opaque heap allocations.  We enforce
// exclusive ownership (the `Option` ensures the pointer is not aliased), so
// it is safe to send `NssHashState` between threads.
unsafe impl Send for NssHashState {}

impl crate::crypto::HashState for NssHashState {
    fn update(&mut self, data: &[u8]) {
        let ctx = self
            .ctx
            .expect("NssHashState::update called after finalize")
            .as_ptr();

        // SAFETY: ctx is non-null; data is a valid readable slice.
        let status = unsafe { PK11_DigestOp(ctx, data.as_ptr(), data.len() as std::ffi::c_uint) };
        assert_eq!(
            status,
            nss_sys::SECStatus::SECSuccess,
            "PK11_DigestOp failed"
        );
    }

    fn finalize_boxed(mut self: Box<Self>) -> Vec<u8> {
        // Take the pointer so `Drop` sees `None` and skips the destroy call.
        let ctx = self
            .ctx
            .take()
            .expect("NssHashState::finalize_boxed called after finalize")
            .as_ptr();

        let mut out = vec![0u8; self.output_len];
        let mut out_len: std::ffi::c_uint = 0;

        // SAFETY: ctx is non-null; out is a valid writable buffer.
        let status = unsafe {
            PK11_DigestFinal(
                ctx,
                out.as_mut_ptr(),
                &mut out_len,
                self.output_len as std::ffi::c_uint,
            )
        };

        // SAFETY: ctx is non-null and was not yet destroyed (ctx is taken above).
        unsafe { PK11_DestroyContext(ctx, PR_TRUE) };

        assert_eq!(
            status,
            nss_sys::SECStatus::SECSuccess,
            "PK11_DigestFinal failed"
        );
        out.truncate(out_len as usize);
        out
    }
}

impl Drop for NssHashState {
    fn drop(&mut self) {
        // ctx is `None` when `finalize_boxed` already destroyed the context.
        if let Some(ctx) = self.ctx.take() {
            // SAFETY: ctx is non-null and we have exclusive ownership.
            unsafe { PK11_DestroyContext(ctx.as_ptr(), PR_TRUE) };
        }
    }
}

// ── StreamingHasher / ErasedStreamingHasher for NssDataHasher ────────────────

impl crate::crypto::StreamingHasher for NssDataHasher {
    type Error = NssDataHasherError;

    fn new_hash(
        &self,
        algorithm: &str,
    ) -> Result<Box<dyn crate::crypto::HashState>, NssDataHasherError> {
        if !ensure_nss_init() {
            return Err(NssDataHasherError("NSS initialisation failed".into()));
        }

        let (nss_tag, output_len) = super::alg_name_to_hash_tag(algorithm).ok_or_else(|| {
            NssDataHasherError(format!(
                "unsupported hash algorithm: {algorithm} \
                 (accepted: md5, sha1, sha224, sha256, sha384, sha512)"
            ))
        })?;

        // SAFETY: NSS is initialized; nss_tag is a valid SECOidTag for a hash alg.
        let raw_ctx = unsafe { PK11_CreateDigestContext(nss_tag) };
        if raw_ctx.is_null() {
            return Err(NssDataHasherError("PK11_CreateDigestContext failed".into()));
        }

        // SAFETY: raw_ctx is non-null.
        let status = unsafe { PK11_DigestBegin(raw_ctx) };
        if status != nss_sys::SECStatus::SECSuccess {
            unsafe { PK11_DestroyContext(raw_ctx, PR_TRUE) };
            return Err(NssDataHasherError("PK11_DigestBegin failed".into()));
        }

        Ok(Box::new(NssHashState {
            ctx: Some(std::ptr::NonNull::new(raw_ctx).unwrap()),
            output_len,
        }))
    }
}

impl crate::crypto::ErasedStreamingHasher for NssDataHasher {
    fn new_hash_erased(
        &self,
        algorithm: &str,
    ) -> Result<Box<dyn crate::crypto::HashState>, crate::crypto::PrivateKeyError> {
        use crate::crypto::StreamingHasher as _;
        self.new_hash(algorithm)
            .map_err(crate::crypto::PrivateKeyError::new)
    }
}

/// Return a boxed [`crate::ErasedStreamingHasher`] backed by NSS.
///
/// Called by [`crate::default_streaming_hasher`] when the `nss` feature is
/// enabled.  Callers never need to name [`NssDataHasher`].
pub(crate) fn nss_streaming_hasher() -> Box<dyn crate::crypto::ErasedStreamingHasher> {
    Box::new(NssDataHasher)
}

// ── HMAC algorithm-name helper ────────────────────────────────────────────────

fn alg_name_to_hmac_mech(algorithm: &str) -> Option<(CKMechanismType, usize)> {
    match algorithm {
        "md5" => Some((CKM_MD5_HMAC, 16)),
        "sha1" => Some((CKM_SHA_1_HMAC, 20)),
        "sha224" => Some((CKM_SHA224_HMAC, 28)),
        "sha256" => Some((CKM_SHA256_HMAC, 32)),
        "sha384" => Some((CKM_SHA384_HMAC, 48)),
        "sha512" => Some((CKM_SHA512_HMAC, 64)),
        _ => None,
    }
}

// ── NssDataHasher ─────────────────────────────────────────────────────────────

/// Error type for [`NssDataHasher`].
#[derive(Debug)]
pub struct NssDataHasherError(String);

impl std::fmt::Display for NssDataHasherError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for NssDataHasherError {}

/// NSS-backed [`DataHasher`] using `PK11_HashBuf`.
///
/// Supports `"sha1"`, `"sha256"`, `"sha384"`, and `"sha512"`.
pub struct NssDataHasher;

impl DataHasher for NssDataHasher {
    type Error = NssDataHasherError;

    fn hash_data(&self, algorithm: &str, data: &[u8]) -> Result<Vec<u8>, NssDataHasherError> {
        if !ensure_nss_init() {
            return Err(NssDataHasherError("NSS initialisation failed".into()));
        }

        let (nss_tag, output_len) = alg_name_to_hash_tag(algorithm).ok_or_else(|| {
            NssDataHasherError(format!(
                "unsupported hash algorithm: {algorithm} \
                 (accepted: md5, sha1, sha224, sha256, sha384, sha512)"
            ))
        })?;

        // Use the streaming digest-context path rather than PK11_HashBuf.
        // PK11_HashBuf does not support SHA-224 on Fedora NSS builds.  The
        // streaming path (PK11_CreateDigestContext → PK11_DigestBegin →
        // PK11_DigestOp → PK11_DigestFinal) supports all algorithms that the
        // installed NSS library can hash, including SHA-224.
        //
        // SAFETY: NSS is initialized; nss_tag is a valid SECOidTag for a hash alg.
        let raw_ctx = unsafe { PK11_CreateDigestContext(nss_tag) };
        if raw_ctx.is_null() {
            return Err(NssDataHasherError(format!(
                "PK11_CreateDigestContext failed for {algorithm}"
            )));
        }

        // PK11_CreateDigestContext leaves init=PR_FALSE; PK11_DigestBegin
        // calls C_DigestInit to complete initialization.
        // SAFETY: raw_ctx is non-null.
        let status = unsafe { PK11_DigestBegin(raw_ctx) };
        if status != nss_sys::SECStatus::SECSuccess {
            unsafe { PK11_DestroyContext(raw_ctx, PR_TRUE) };
            return Err(NssDataHasherError("PK11_DigestBegin failed".into()));
        }

        if !data.is_empty() {
            // SAFETY: raw_ctx is non-null; data is a valid readable slice.
            let status =
                unsafe { PK11_DigestOp(raw_ctx, data.as_ptr(), data.len() as std::ffi::c_uint) };
            if status != nss_sys::SECStatus::SECSuccess {
                unsafe { PK11_DestroyContext(raw_ctx, PR_TRUE) };
                return Err(NssDataHasherError("PK11_DigestOp failed".into()));
            }
        }

        let mut out = vec![0u8; output_len];
        let mut out_len: std::ffi::c_uint = 0;

        // SAFETY: raw_ctx is non-null; out is a valid writable buffer.
        let status = unsafe {
            PK11_DigestFinal(
                raw_ctx,
                out.as_mut_ptr(),
                &mut out_len,
                output_len as std::ffi::c_uint,
            )
        };
        // SAFETY: raw_ctx is non-null and not yet destroyed.
        unsafe { PK11_DestroyContext(raw_ctx, PR_TRUE) };

        if status != nss_sys::SECStatus::SECSuccess {
            return Err(NssDataHasherError("PK11_DigestFinal failed".into()));
        }

        out.truncate(out_len as usize);
        Ok(out)
    }
}

impl ErasedDataHasher for NssDataHasher {
    fn hash_data_erased(&self, algorithm: &str, data: &[u8]) -> Result<Vec<u8>, PrivateKeyError> {
        self.hash_data(algorithm, data)
            .map_err(PrivateKeyError::new)
    }
}

// ── NssHmacProvider ───────────────────────────────────────────────────────────

/// Error type for [`NssHmacProvider`].
#[derive(Debug)]
pub struct NssHmacError(String);

impl std::fmt::Display for NssHmacError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for NssHmacError {}

/// NSS-backed [`HmacProvider`] using a pure-Rust RFC 2104 HMAC construction
/// over the NSS streaming-hash path (`PK11_CreateDigestContext`).
///
/// PKCS#11 symmetric-key HMAC (`PK11_CreateContextBySymKey` + `PK11_DigestFinal`)
/// fails from Rust FFI on Fedora NSS — `C_SignFinal` returns
/// `SEC_ERROR_BAD_SIGNATURE` even after `PK11_DigestBegin`.  The pure-Rust
/// construction avoids `PK11_CreateContextBySymKey` entirely and only relies on
/// the NSS digest-context path, which works correctly from non-NSPR threads.
///
/// Supports `"md5"`, `"sha1"`, `"sha256"`, `"sha384"`, and `"sha512"`.
pub struct NssHmacProvider;

/// HMAC inner-hash block size for a given algorithm name.
///
/// Returns `None` for unknown algorithm names.
fn hmac_block_size_for_alg(algorithm: &str) -> Option<usize> {
    match algorithm {
        "md5" | "sha1" | "sha224" | "sha256" => Some(64),
        "sha384" | "sha512" => Some(128),
        _ => None,
    }
}

/// Pure-Rust RFC 2104 HMAC using `NssDataHasher` for the underlying hash.
///
/// `HMAC(K, m) = H((K XOR opad) ∥ H((K XOR ipad) ∥ m))`
///
/// - If `|K| > B` the key is pre-hashed: `K = H(K)`.
/// - If `|K| < B` the key is zero-padded to `B` bytes.
/// - `ipad = 0x36` repeated `B` times; `opad = 0x5c` repeated `B` times.
fn nss_hmac_compute_rust(
    algorithm: &str,
    block_size: usize,
    key: &[u8],
    data: &[u8],
) -> Result<Vec<u8>, NssHmacError> {
    let hasher = NssDataHasher;

    // Pre-hash overlong keys (RFC 2104 §2).
    let key_hashed;
    let key = if key.len() > block_size {
        key_hashed = hasher
            .hash_data(algorithm, key)
            .map_err(|e| NssHmacError(e.to_string()))?;
        &key_hashed[..]
    } else {
        key
    };

    // Pad key to block_size with trailing zeros.
    let mut k = vec![0u8; block_size];
    k[..key.len()].copy_from_slice(key);

    // Inner hash: H((K XOR ipad) ∥ data)
    let mut inner: Vec<u8> = Vec::with_capacity(block_size + data.len());
    for &b in &k {
        inner.push(b ^ 0x36);
    }
    inner.extend_from_slice(data);
    let inner_hash = hasher
        .hash_data(algorithm, &inner)
        .map_err(|e| NssHmacError(e.to_string()))?;

    // Outer hash: H((K XOR opad) ∥ inner_hash)
    let mut outer: Vec<u8> = Vec::with_capacity(block_size + inner_hash.len());
    for &b in &k {
        outer.push(b ^ 0x5c);
    }
    outer.extend_from_slice(&inner_hash);
    hasher
        .hash_data(algorithm, &outer)
        .map_err(|e| NssHmacError(e.to_string()))
}

impl HmacProvider for NssHmacProvider {
    type Error = NssHmacError;

    fn hmac_compute(
        &self,
        algorithm: &str,
        key: &[u8],
        data: &[u8],
    ) -> Result<Vec<u8>, NssHmacError> {
        let block_size = hmac_block_size_for_alg(algorithm).ok_or_else(|| {
            NssHmacError(format!(
                "unsupported HMAC algorithm: {algorithm} \
                 (accepted: md5, sha1, sha256, sha384, sha512)"
            ))
        })?;
        nss_hmac_compute_rust(algorithm, block_size, key, data)
    }

    fn hmac_verify(
        &self,
        algorithm: &str,
        key: &[u8],
        data: &[u8],
        expected: &[u8],
    ) -> Result<(), NssHmacError> {
        let mac = self.hmac_compute(algorithm, key, data)?;
        if constant_time_eq(&mac, expected) {
            Ok(())
        } else {
            Err(NssHmacError("HMAC verification failed".into()))
        }
    }
}

impl ErasedHmacProvider for NssHmacProvider {
    fn hmac_compute_erased(
        &self,
        algorithm: &str,
        key: &[u8],
        data: &[u8],
    ) -> Result<Vec<u8>, PrivateKeyError> {
        self.hmac_compute(algorithm, key, data)
            .map_err(PrivateKeyError::new)
    }

    fn hmac_verify_erased(
        &self,
        algorithm: &str,
        key: &[u8],
        data: &[u8],
        expected: &[u8],
    ) -> Result<(), PrivateKeyError> {
        self.hmac_verify(algorithm, key, data, expected)
            .map_err(PrivateKeyError::new)
    }
}

// ── Factory functions ─────────────────────────────────────────────────────────

/// Return a boxed [`crate::ErasedDataHasher`] backed by NSS.
///
/// Called by [`crate::default_data_hasher`] when the `nss` feature is enabled.
/// Callers never need to name `NssDataHasher`.
pub(crate) fn nss_data_hasher() -> Box<dyn ErasedDataHasher> {
    Box::new(NssDataHasher)
}

/// Return a boxed [`crate::ErasedHmacProvider`] backed by NSS.
///
/// Called by [`crate::default_hmac_provider`] when the `nss` feature is enabled.
/// Callers never need to name `NssHmacProvider`.
pub(crate) fn nss_hmac_provider() -> Box<dyn ErasedHmacProvider> {
    Box::new(NssHmacProvider)
}

// ── SecureRandom for NssDataHasher ────────────────────────────────────────────

impl SecureRandom for NssDataHasher {
    type Error = NssDataHasherError;

    fn rand_bytes(&self, out: &mut [u8]) -> Result<(), NssDataHasherError> {
        if !ensure_nss_init() {
            return Err(NssDataHasherError("NSS initialisation failed".into()));
        }
        if out.is_empty() {
            return Ok(());
        }
        // SAFETY: `out` is a valid writable slice of `out.len()` bytes;
        // `PK11_GenerateRandom` fills it with CSPRNG output.
        let status = unsafe { PK11_GenerateRandom(out.as_mut_ptr(), out.len() as std::ffi::c_int) };
        if status == nss_sys::SECStatus::SECSuccess {
            Ok(())
        } else {
            Err(NssDataHasherError("PK11_GenerateRandom failed".into()))
        }
    }
}

pub(crate) fn nss_secure_random() -> NssDataHasher {
    NssDataHasher
}

// ── Pbkdf2Provider for NssHmacProvider ───────────────────────────────────────
//
// PBKDF2-HMAC is a sequence of HMAC calls (RFC 8018 §5.2); no new FFI
// is needed — it is implemented in pure Rust on top of `NssHmacProvider`.

impl Pbkdf2Provider for NssHmacProvider {
    type Error = NssHmacError;

    fn pbkdf2_hmac(
        &self,
        algorithm: &str,
        password: &[u8],
        salt: &[u8],
        iterations: usize,
        length: usize,
    ) -> Result<Vec<u8>, NssHmacError> {
        if length == 0 {
            return Ok(Vec::new());
        }
        let (_, hash_len) = alg_name_to_hmac_mech(algorithm).ok_or_else(|| {
            NssHmacError(format!(
                "unsupported PBKDF2 algorithm: {algorithm} \
                 (accepted: md5, sha1, sha224, sha256, sha384, sha512)"
            ))
        })?;
        if iterations == 0 {
            return Err(NssHmacError("PBKDF2 iterations must be >= 1".into()));
        }

        let blocks = length.div_ceil(hash_len);
        let mut dk = Vec::with_capacity(length);

        for block_idx in 1u32..=(blocks as u32) {
            // U1 = PRF(Password, Salt || INT(i))
            let mut input = Vec::with_capacity(salt.len() + 4);
            input.extend_from_slice(salt);
            input.extend_from_slice(&block_idx.to_be_bytes());
            let mut u = self.hmac_compute(algorithm, password, &input)?;
            let mut f = u.clone();

            for _ in 1..iterations {
                u = self.hmac_compute(algorithm, password, &u)?;
                for (a, b) in f.iter_mut().zip(u.iter()) {
                    *a ^= b;
                }
            }
            dk.extend_from_slice(&f);
        }

        dk.truncate(length);
        Ok(dk)
    }
}

pub(crate) fn nss_pbkdf2_provider() -> NssHmacProvider {
    NssHmacProvider
}

// ── Streaming HMAC for NssHmacProvider ───────────────────────────────────────

/// Live streaming HMAC state backed by pure-Rust RFC 2104 HMAC.
///
/// Holds `(K XOR opad)` and an incremental NSS digest-context for the inner
/// hash `H((K XOR ipad) ∥ data…)`.  `finalize_boxed` completes the inner hash,
/// then computes the outer hash `H((K XOR opad) ∥ inner_hash)` in one shot.
struct NssHmacStateRust {
    /// `(K XOR opad)`, `block_size` bytes.
    opad_key: Vec<u8>,
    /// Streaming inner hash `H((K XOR ipad) ∥ data…)`.
    inner_state: Box<dyn crate::crypto::HashState>,
    /// Algorithm name for the outer hash call.
    algorithm: String,
}

// SAFETY: `NssHmacStateRust` owns the inner `NssHashState` (which is `Send`)
// and plain `Vec<u8>` / `String`.  No raw pointers are shared across threads.
unsafe impl Send for NssHmacStateRust {}

impl HmacState for NssHmacStateRust {
    fn update(&mut self, data: &[u8]) {
        self.inner_state.update(data);
    }

    fn finalize_boxed(self: Box<Self>) -> Vec<u8> {
        // Complete inner hash: H((K XOR ipad) ∥ data)
        let inner_hash = self.inner_state.finalize_boxed();

        // Outer hash: H((K XOR opad) ∥ inner_hash)
        let mut outer = self.opad_key.clone();
        outer.extend_from_slice(&inner_hash);
        NssDataHasher
            .hash_data(&self.algorithm, &outer)
            .expect("NSS outer HMAC hash failed")
    }
}

impl StreamingHmacProvider for NssHmacProvider {
    type Error = NssHmacError;

    fn new_hmac(&self, algorithm: &str, key: &[u8]) -> Result<Box<dyn HmacState>, NssHmacError> {
        let block_size = hmac_block_size_for_alg(algorithm).ok_or_else(|| {
            NssHmacError(format!(
                "unsupported streaming HMAC algorithm: {algorithm} \
                 (accepted: md5, sha1, sha256, sha384, sha512)"
            ))
        })?;

        let hasher = NssDataHasher;

        // Pre-hash overlong keys (RFC 2104 §2).
        let key_hashed;
        let key = if key.len() > block_size {
            key_hashed = hasher
                .hash_data(algorithm, key)
                .map_err(|e| NssHmacError(e.to_string()))?;
            &key_hashed[..]
        } else {
            key
        };

        // Pad key to block_size with trailing zeros.
        let mut k = vec![0u8; block_size];
        k[..key.len()].copy_from_slice(key);

        let ipad_key: Vec<u8> = k.iter().map(|b| b ^ 0x36).collect();
        let opad_key: Vec<u8> = k.iter().map(|b| b ^ 0x5c).collect();

        // Seed the inner streaming hash with (K XOR ipad).
        use crate::crypto::StreamingHasher as _;
        let mut inner_state = hasher
            .new_hash(algorithm)
            .map_err(|e| NssHmacError(e.to_string()))?;
        inner_state.update(&ipad_key);

        Ok(Box::new(NssHmacStateRust {
            opad_key,
            inner_state,
            algorithm: algorithm.to_string(),
        }))
    }
}

impl ErasedStreamingHmacProvider for NssHmacProvider {
    fn new_hmac_erased(
        &self,
        algorithm: &str,
        key: &[u8],
    ) -> Result<Box<dyn HmacState>, PrivateKeyError> {
        use crate::crypto::StreamingHmacProvider as _;
        self.new_hmac(algorithm, key).map_err(PrivateKeyError::new)
    }
}

pub(crate) fn nss_streaming_hmac_provider() -> Box<dyn ErasedStreamingHmacProvider> {
    Box::new(NssHmacProvider)
}

// ── BlockCipherProvider for NssDataHasher ─────────────────────────────────────

/// Import a symmetric key for AES-CBC or 3DES-CBC and perform one-shot
/// encrypt or decrypt using the explicit PKCS#11 context path.
///
/// ## Why not `PK11_Encrypt` / `PK11_Decrypt`?
///
/// `PK11_Encrypt` internally calls `PK11_CreateContextBySymKey` + `PK11_CipherOp`
/// + `PK11_DigestFinal` but **never calls `PK11_DigestBegin`**.
/// `PK11_CreateContextBySymKey` creates a context with `init = PR_FALSE`; the
/// subsequent `PK11_CipherOp` checks `init` and fails immediately.  This is a
/// silent NSS bug that only manifests when the PKCS#11 session is created from
/// a non-NSPR thread (i.e. from Rust).  The fix is to perform the same sequence
/// manually but with an explicit `PK11_DigestBegin` call.
fn nss_block_cipher_op(
    mechanism: CKMechanismType,
    encrypt: bool,
    key: &[u8],
    iv: &[u8],
    input: &[u8],
    block_size: usize,
) -> Result<Vec<u8>, NssDataHasherError> {
    if !ensure_nss_init() {
        return Err(NssDataHasherError("NSS initialisation failed".into()));
    }

    // ── Import the symmetric key ──────────────────────────────────────────────

    // SAFETY: PK11_GetInternalSlot is thread-safe after NSS_NoDB_Init.
    let slot = unsafe { PK11_GetInternalSlot() };
    if slot.is_null() {
        return Err(NssDataHasherError("PK11_GetInternalSlot failed".into()));
    }

    let key_item = SECItemStr {
        type_: SECItemType::siBuffer,
        data: key.as_ptr() as *mut _,
        len: key.len() as u32,
    };
    let operation = if encrypt { CKA_ENCRYPT } else { CKA_DECRYPT };

    // SAFETY: slot and key_item are valid for the duration of this call.
    let sym_key = unsafe {
        PK11_ImportSymKey(
            slot,
            mechanism,
            PK11_ORIGIN_UNWRAP,
            operation,
            &key_item,
            std::ptr::null_mut(),
        )
    };
    // Release slot reference — sym_key holds its own.
    unsafe { PK11_FreeSlot(slot) };

    if sym_key.is_null() {
        return Err(NssDataHasherError("PK11_ImportSymKey failed".into()));
    }

    // ── Create the cipher context (IV as param) ───────────────────────────────

    // For AES-CBC / 3DES-CBC the param is the IV as a raw siBuffer.
    let iv_item = SECItemStr {
        type_: SECItemType::siBuffer,
        data: iv.as_ptr() as *mut _,
        len: iv.len() as u32,
    };

    // SAFETY: sym_key is non-null; iv_item.data points into `iv` which outlives this scope.
    let ctx = unsafe { PK11_CreateContextBySymKey(mechanism, operation, sym_key, &iv_item) };
    if ctx.is_null() {
        unsafe { PK11_FreeSymKey(sym_key) };
        return Err(NssDataHasherError(
            "PK11_CreateContextBySymKey failed".into(),
        ));
    }

    // PK11_CreateContextBySymKey leaves init=PR_FALSE.  PK11_DigestBegin calls
    // C_EncryptInit / C_DecryptInit on the underlying PKCS#11 session, which
    // sets init=PR_TRUE.  Without this, PK11_CipherOp returns immediately with
    // SEC_ERROR_LIBRARY_FAILURE because it sees init=PR_FALSE.
    // SAFETY: ctx is non-null.
    let init_status = unsafe { PK11_DigestBegin(ctx) };
    if init_status != nss_sys::SECStatus::SECSuccess {
        unsafe {
            PK11_DestroyContext(ctx, PR_TRUE);
            PK11_FreeSymKey(sym_key);
        }
        return Err(NssDataHasherError("PK11_DigestBegin failed".into()));
    }

    // ── Feed data via streaming cipher op ─────────────────────────────────────

    // Allocate output buffer: input + one block is always sufficient for
    // padding modes; for non-padding modes the output equals the input.
    let max_out = input.len() + block_size;
    let mut out = vec![0u8; max_out];
    let mut partial_len: std::ffi::c_int = 0;

    // SAFETY: ctx is non-null; all slice pointers are valid for this call.
    let cipher_status = unsafe {
        PK11_CipherOp(
            ctx,
            out.as_mut_ptr(),
            &mut partial_len,
            max_out as std::ffi::c_int,
            input.as_ptr(),
            input.len() as std::ffi::c_int,
        )
    };

    if cipher_status != nss_sys::SECStatus::SECSuccess {
        unsafe {
            PK11_DestroyContext(ctx, PR_TRUE);
            PK11_FreeSymKey(sym_key);
        }
        return Err(NssDataHasherError(format!(
            "NSS PK11_CipherOp ({}) failed",
            if encrypt { "encrypt" } else { "decrypt" }
        )));
    }

    // ── Finalise (flush padding block for PAD modes) ──────────────────────────

    let partial_ulen = partial_len as usize;
    let remaining = max_out - partial_ulen;
    let mut final_len: std::ffi::c_uint = 0;

    // SAFETY: ctx is non-null; out[partial_ulen..] is a valid writable region.
    let final_status = unsafe {
        PK11_DigestFinal(
            ctx,
            out[partial_ulen..].as_mut_ptr(),
            &mut final_len,
            remaining as std::ffi::c_uint,
        )
    };

    // SAFETY: ctx and sym_key are non-null.
    unsafe {
        PK11_DestroyContext(ctx, PR_TRUE);
        PK11_FreeSymKey(sym_key);
    }

    if final_status != nss_sys::SECStatus::SECSuccess {
        return Err(NssDataHasherError(format!(
            "NSS PK11_DigestFinal ({}) failed",
            if encrypt { "encrypt" } else { "decrypt" }
        )));
    }

    out.truncate(partial_ulen + final_len as usize);
    Ok(out)
}

// ── AES-GCM (PKCS#11 CKM_AES_GCM) ───────────────────────────────────────────

/// Encrypt `plaintext` with AES-GCM, returning `ciphertext ‖ tag[16]`.
///
/// Uses the same `PK11_CreateContextBySymKey` + `PK11_DigestBegin` workaround
/// as `nss_block_cipher_op`.  For GCM, `PK11_CipherOp` produces ciphertext
/// (same length as plaintext) and `PK11_DigestFinal` produces the 16-byte tag.
fn nss_aes_gcm_encrypt(
    key: &[u8],
    nonce: &[u8],
    plaintext: &[u8],
    aad: &[u8],
) -> Result<Vec<u8>, NssDataHasherError> {
    nss_aes_gcm_op(true, key, nonce, plaintext, aad)
}

/// Decrypt and verify `ciphertext_with_tag` (last 16 bytes = auth tag).
///
/// Returns `Err` if `PK11_DigestFinal` reports a tag mismatch.
fn nss_aes_gcm_decrypt(
    key: &[u8],
    nonce: &[u8],
    ciphertext_with_tag: &[u8],
    aad: &[u8],
) -> Result<Vec<u8>, NssDataHasherError> {
    if ciphertext_with_tag.len() < 16 {
        return Err(NssDataHasherError(
            "AES-GCM input too short (must be at least 16 bytes for the tag)".into(),
        ));
    }
    nss_aes_gcm_op(false, key, nonce, ciphertext_with_tag, aad)
}

fn nss_aes_gcm_op(
    encrypt: bool,
    key: &[u8],
    nonce: &[u8],
    input: &[u8],
    aad: &[u8],
) -> Result<Vec<u8>, NssDataHasherError> {
    if !matches!(key.len(), 16 | 24 | 32) {
        return Err(NssDataHasherError(
            "AES-GCM key must be 16, 24, or 32 bytes".into(),
        ));
    }
    if nonce.len() != 12 {
        return Err(NssDataHasherError("AES-GCM nonce must be 12 bytes".into()));
    }

    if !ensure_nss_init() {
        return Err(NssDataHasherError("NSS initialisation failed".into()));
    }

    // Build PKCS#11 v2.40 CK_GCM_PARAMS.  The struct must stay alive for the
    // entire duration of the PKCS#11 calls below (it is stack-allocated here).
    let gcm_params = CkAesGcmParams {
        iv_ptr: nonce.as_ptr(),
        iv_len: nonce.len() as std::ffi::c_ulong,
        iv_bits: (nonce.len() * 8) as std::ffi::c_ulong,
        aad_ptr: if aad.is_empty() {
            std::ptr::null()
        } else {
            aad.as_ptr()
        },
        aad_len: aad.len() as std::ffi::c_ulong,
        tag_bits: 128,
    };
    let param_item = SECItemStr {
        type_: SECItemType::siBuffer,
        data: &gcm_params as *const CkAesGcmParams as *mut u8,
        len: std::mem::size_of::<CkAesGcmParams>() as u32,
    };

    // ── Import the symmetric key ──────────────────────────────────────────────
    let slot = unsafe { PK11_GetInternalSlot() };
    if slot.is_null() {
        return Err(NssDataHasherError("PK11_GetInternalSlot failed".into()));
    }
    let key_item = SECItemStr {
        type_: SECItemType::siBuffer,
        data: key.as_ptr() as *mut _,
        len: key.len() as u32,
    };
    let operation = if encrypt { CKA_ENCRYPT } else { CKA_DECRYPT };
    let sym_key = unsafe {
        PK11_ImportSymKey(
            slot,
            CKM_AES_GCM,
            PK11_ORIGIN_UNWRAP,
            operation,
            &key_item,
            std::ptr::null_mut(),
        )
    };
    unsafe { PK11_FreeSlot(slot) };
    if sym_key.is_null() {
        return Err(NssDataHasherError("PK11_ImportSymKey failed".into()));
    }

    // ── Create cipher context with GCM params ─────────────────────────────────
    let ctx = unsafe { PK11_CreateContextBySymKey(CKM_AES_GCM, operation, sym_key, &param_item) };
    if ctx.is_null() {
        unsafe { PK11_FreeSymKey(sym_key) };
        return Err(NssDataHasherError(
            "PK11_CreateContextBySymKey failed".into(),
        ));
    }
    // Same PK11_DigestBegin workaround as nss_block_cipher_op.
    let init_status = unsafe { PK11_DigestBegin(ctx) };
    if init_status != nss_sys::SECStatus::SECSuccess {
        unsafe {
            PK11_DestroyContext(ctx, nss_sys::nspr::PR_TRUE);
            PK11_FreeSymKey(sym_key);
        }
        return Err(NssDataHasherError("PK11_DigestBegin failed".into()));
    }

    // ── Feed data ─────────────────────────────────────────────────────────────
    // For encrypt: PK11_CipherOp writes ciphertext (input.len() bytes);
    //              PK11_DigestFinal writes the 16-byte tag.
    // For decrypt: NSS buffers the last 16 bytes of input as the expected tag;
    //              PK11_CipherOp writes input.len()-16 bytes of plaintext;
    //              PK11_DigestFinal verifies the tag and writes any remainder
    //              (may be 0), returning SECFailure on mismatch.
    let max_out = input.len() + 16; // enough for both directions
    let mut out = vec![0u8; max_out];
    let mut partial_len: std::ffi::c_int = 0;
    let cipher_status = unsafe {
        PK11_CipherOp(
            ctx,
            out.as_mut_ptr(),
            &mut partial_len,
            max_out as std::ffi::c_int,
            input.as_ptr(),
            input.len() as std::ffi::c_int,
        )
    };
    if cipher_status != nss_sys::SECStatus::SECSuccess {
        unsafe {
            PK11_DestroyContext(ctx, nss_sys::nspr::PR_TRUE);
            PK11_FreeSymKey(sym_key);
        }
        return Err(NssDataHasherError(format!(
            "NSS PK11_CipherOp (AES-GCM {}) failed",
            if encrypt { "encrypt" } else { "decrypt" }
        )));
    }

    let partial_ulen = partial_len as usize;
    let remaining = max_out - partial_ulen;
    let mut final_len: std::ffi::c_uint = 0;
    let final_status = unsafe {
        PK11_DigestFinal(
            ctx,
            out[partial_ulen..].as_mut_ptr(),
            &mut final_len,
            remaining as std::ffi::c_uint,
        )
    };
    unsafe {
        PK11_DestroyContext(ctx, nss_sys::nspr::PR_TRUE);
        PK11_FreeSymKey(sym_key);
    }
    if final_status != nss_sys::SECStatus::SECSuccess {
        return Err(NssDataHasherError(if encrypt {
            "NSS PK11_DigestFinal (AES-GCM encrypt) failed".into()
        } else {
            "AES-GCM authentication tag mismatch".into()
        }));
    }

    out.truncate(partial_ulen + final_len as usize);
    Ok(out)
}

impl BlockCipherProvider for NssDataHasher {
    type Error = NssDataHasherError;

    fn aes_cbc_encrypt(
        &self,
        key: &[u8],
        iv: &[u8],
        plaintext: &[u8],
        pad: bool,
    ) -> Result<Vec<u8>, NssDataHasherError> {
        if key.len() != 16 && key.len() != 24 && key.len() != 32 {
            return Err(NssDataHasherError(format!(
                "invalid AES key length: {} (must be 16, 24, or 32)",
                key.len()
            )));
        }
        if iv.len() != 16 {
            return Err(NssDataHasherError(format!(
                "invalid AES-CBC IV length: {} (must be 16)",
                iv.len()
            )));
        }
        let mech = if pad { CKM_AES_CBC_PAD } else { CKM_AES_CBC };
        nss_block_cipher_op(mech, true, key, iv, plaintext, 16)
    }

    fn aes_cbc_decrypt(
        &self,
        key: &[u8],
        iv: &[u8],
        ciphertext: &[u8],
        unpad: bool,
    ) -> Result<Vec<u8>, NssDataHasherError> {
        if key.len() != 16 && key.len() != 24 && key.len() != 32 {
            return Err(NssDataHasherError(format!(
                "invalid AES key length: {} (must be 16, 24, or 32)",
                key.len()
            )));
        }
        if iv.len() != 16 {
            return Err(NssDataHasherError(format!(
                "invalid AES-CBC IV length: {} (must be 16)",
                iv.len()
            )));
        }
        let mech = if unpad { CKM_AES_CBC_PAD } else { CKM_AES_CBC };
        nss_block_cipher_op(mech, false, key, iv, ciphertext, 16)
    }

    fn des3_cbc_encrypt(
        &self,
        key: &[u8],
        iv: &[u8],
        plaintext: &[u8],
        pad: bool,
    ) -> Result<Vec<u8>, NssDataHasherError> {
        if key.len() != 16 && key.len() != 24 {
            return Err(NssDataHasherError(format!(
                "invalid 3DES key length: {} (must be 16 or 24)",
                key.len()
            )));
        }
        if iv.len() != 8 {
            return Err(NssDataHasherError(format!(
                "invalid 3DES-CBC IV length: {} (must be 8)",
                iv.len()
            )));
        }
        let mech = if pad { CKM_DES3_CBC_PAD } else { CKM_DES3_CBC };
        nss_block_cipher_op(mech, true, key, iv, plaintext, 8)
    }

    fn des3_cbc_decrypt(
        &self,
        key: &[u8],
        iv: &[u8],
        ciphertext: &[u8],
        unpad: bool,
    ) -> Result<Vec<u8>, NssDataHasherError> {
        if key.len() != 16 && key.len() != 24 {
            return Err(NssDataHasherError(format!(
                "invalid 3DES key length: {} (must be 16 or 24)",
                key.len()
            )));
        }
        if iv.len() != 8 {
            return Err(NssDataHasherError(format!(
                "invalid 3DES-CBC IV length: {} (must be 8)",
                iv.len()
            )));
        }
        let mech = if unpad {
            CKM_DES3_CBC_PAD
        } else {
            CKM_DES3_CBC
        };
        nss_block_cipher_op(mech, false, key, iv, ciphertext, 8)
    }

    fn aes_gcm_encrypt(
        &self,
        key: &[u8],
        nonce: &[u8],
        plaintext: &[u8],
        aad: &[u8],
    ) -> Result<Vec<u8>, NssDataHasherError> {
        nss_aes_gcm_encrypt(key, nonce, plaintext, aad)
    }

    fn aes_gcm_decrypt(
        &self,
        key: &[u8],
        nonce: &[u8],
        ciphertext_with_tag: &[u8],
        aad: &[u8],
    ) -> Result<Vec<u8>, NssDataHasherError> {
        nss_aes_gcm_decrypt(key, nonce, ciphertext_with_tag, aad)
    }
}

pub(crate) fn nss_block_cipher_provider() -> NssDataHasher {
    NssDataHasher
}