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
//! Backend-agnostic CMS, PKCS#12, and key-transport implementations.
//!
//! All crypto work is delegated to the active backend via
//! [`crate::default_block_cipher_provider`], [`crate::default_pbkdf2_provider`],
//! [`crate::default_secure_random`], and the [`BackendPublicKey`] /
//! [`BackendPrivateKey`] RSA helpers.  These types therefore work with both the
//! `openssl` and `nss` features without any per-call `#[cfg]` guards.

use super::utils::split_alg_id;
use super::{
    BackendPrivateKey, BackendPublicKey, BlockCipherProvider, HmacProvider, Pbkdf2Provider,
    SecureRandom,
};
use crate::pkcs12_types::{
    Pbes2Params, Pbkdf2Params, ID_AES128_CBC, ID_AES192_CBC, ID_AES256_CBC, ID_HMAC_WITH_SHA1,
    ID_HMAC_WITH_SHA256, ID_HMAC_WITH_SHA384, ID_HMAC_WITH_SHA512, ID_PBES2, ID_PBKDF2,
};
use synta::{Decoder, Encoding, TagClass};

// ── Error ─────────────────────────────────────────────────────────────────────

/// Error returned by [`DefaultCrypto`] and [`DefaultEnvelopedDataDecryptor`].
#[derive(Debug)]
pub enum DefaultCryptoError {
    /// ASN.1 parse or encoding error.
    Parse(synta::Error),
    /// The algorithm or cipher OID is not supported.
    UnsupportedAlgorithm(String),
    /// The active crypto backend reported an error.
    Backend(String),
}

impl std::fmt::Display for DefaultCryptoError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DefaultCryptoError::Parse(e) => write!(f, "ASN.1 error: {:?}", e),
            DefaultCryptoError::UnsupportedAlgorithm(s) => {
                write!(f, "unsupported algorithm: {}", s)
            }
            DefaultCryptoError::Backend(s) => write!(f, "crypto backend error: {}", s),
        }
    }
}

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

impl From<synta::Error> for DefaultCryptoError {
    fn from(e: synta::Error) -> Self {
        DefaultCryptoError::Parse(e)
    }
}

// ── Internal helpers ──────────────────────────────────────────────────────────

/// Map an AES-CBC OID to `(key_len_bytes, iv_len_bytes)`.
fn oid_to_aes_params(oid: &[u32]) -> Result<(usize, usize), DefaultCryptoError> {
    if oid == ID_AES128_CBC {
        Ok((16, 16))
    } else if oid == ID_AES192_CBC {
        Ok((24, 16))
    } else if oid == ID_AES256_CBC {
        Ok((32, 16))
    } else {
        Err(DefaultCryptoError::UnsupportedAlgorithm(format!(
            "unsupported cipher OID: {:?}; expected id-aes{{128,192,256}}-cbc",
            oid
        )))
    }
}

/// Map an HMAC PRF OID to the string name accepted by [`crate::Pbkdf2Provider`].
fn oid_to_hmac_alg(oid: &[u32]) -> Result<&'static str, DefaultCryptoError> {
    if oid == ID_HMAC_WITH_SHA1 {
        Ok("sha1")
    } else if oid == ID_HMAC_WITH_SHA256 {
        Ok("sha256")
    } else if oid == ID_HMAC_WITH_SHA384 {
        Ok("sha384")
    } else if oid == ID_HMAC_WITH_SHA512 {
        Ok("sha512")
    } else {
        Err(DefaultCryptoError::UnsupportedAlgorithm(format!(
            "unsupported HMAC PRF OID: {:?}",
            oid
        )))
    }
}

/// Extract the value bytes of an OCTET STRING TLV.
fn decode_octet_string_content(der: &[u8]) -> Result<&[u8], DefaultCryptoError> {
    let mut dec = Decoder::new(der, Encoding::Der);
    let tag = dec.read_tag()?;
    if tag.class() != TagClass::Universal || tag.number() != 4 {
        return Err(DefaultCryptoError::UnsupportedAlgorithm(
            "expected OCTET STRING for cipher IV parameter".into(),
        ));
    }
    let len = dec.read_length()?.definite()?;
    let pos = dec.position();
    Ok(&der[pos..pos + len])
}

/// Build a DER-encoded `AlgorithmIdentifier` for an AES-CBC cipher:
/// `SEQUENCE { OID, OCTET STRING(iv) }`.
fn build_aes_cbc_alg_id(alg_oid: &[u32], iv: &[u8]) -> Result<Vec<u8>, DefaultCryptoError> {
    use synta::{Element, ObjectIdentifier, OctetStringRef};
    let oid = ObjectIdentifier::new(alg_oid).map_err(|_| {
        DefaultCryptoError::UnsupportedAlgorithm(format!("invalid algorithm OID: {:?}", alg_oid))
    })?;
    crate::AlgorithmIdentifier {
        algorithm: oid,
        parameters: Some(Element::OctetString(OctetStringRef::new(iv))),
    }
    .to_der()
    .map_err(DefaultCryptoError::from)
}

/// Build a DER-encoded `AlgorithmIdentifier` for `id-RSAES-OAEP` with
/// SHA-256 hash and MGF1-SHA-256 mask generation (RFC 8017 §A.2.1).
fn build_rsa_oaep_sha256_alg_id() -> Result<Vec<u8>, DefaultCryptoError> {
    use crate::pkcs1_types::{RsaesOaepParams, ID_MGF1, ID_RSAES_OAEP};
    use synta::{Element, ObjectIdentifier};

    let sha256_alg_der = {
        let oid = ObjectIdentifier::new(crate::ID_SHA256)
            .map_err(|_| DefaultCryptoError::UnsupportedAlgorithm("invalid SHA-256 OID".into()))?;
        crate::AlgorithmIdentifier {
            algorithm: oid,
            parameters: None,
        }
        .to_der()?
    };

    let mgf1_alg_der = {
        let oid = ObjectIdentifier::new(ID_MGF1)
            .map_err(|_| DefaultCryptoError::UnsupportedAlgorithm("invalid id-mgf1 OID".into()))?;
        let sha256_elem: Element<'_> = Decoder::new(&sha256_alg_der, Encoding::Der).decode()?;
        crate::AlgorithmIdentifier {
            algorithm: oid,
            parameters: Some(sha256_elem),
        }
        .to_der()?
    };

    let oaep_params_der = {
        let hash_alg: crate::AlgorithmIdentifier<'_> =
            Decoder::new(&sha256_alg_der, Encoding::Der).decode()?;
        let mask_gen: crate::AlgorithmIdentifier<'_> =
            Decoder::new(&mgf1_alg_der, Encoding::Der).decode()?;
        RsaesOaepParams {
            hash_algorithm: Some(hash_alg),
            mask_gen_algorithm: Some(mask_gen),
            p_source_algorithm: None,
        }
        .to_der()?
    };

    let oaep_oid = ObjectIdentifier::new(ID_RSAES_OAEP).map_err(|_| {
        DefaultCryptoError::UnsupportedAlgorithm("invalid id-RSAES-OAEP OID".into())
    })?;
    let oaep_elem: Element<'_> = Decoder::new(&oaep_params_der, Encoding::Der).decode()?;
    crate::AlgorithmIdentifier {
        algorithm: oaep_oid,
        parameters: Some(oaep_elem),
    }
    .to_der()
    .map_err(DefaultCryptoError::from)
}

/// Build a DER-encoded `AlgorithmIdentifier` for `rsaEncryption` with NULL
/// parameters, as used for RSA PKCS#1 v1.5 key transport.
fn build_rsa_pkcs1v15_alg_id() -> Result<Vec<u8>, DefaultCryptoError> {
    use synta::{Element, Null, ObjectIdentifier};
    let oid = ObjectIdentifier::new(crate::RSA_ENCRYPTION).map_err(|_| {
        DefaultCryptoError::UnsupportedAlgorithm("invalid rsaEncryption OID".into())
    })?;
    crate::AlgorithmIdentifier {
        algorithm: oid,
        parameters: Some(Element::Null(Null)),
    }
    .to_der()
    .map_err(DefaultCryptoError::from)
}

// ── DefaultCrypto ─────────────────────────────────────────────────────────────

/// Backend-agnostic crypto provider.
///
/// Implements [`crate::crypto::CmsDecryptor`], [`crate::crypto::Pkcs12Decryptor`],
/// [`crate::crypto::Encryptor`], [`crate::crypto::CmsEncryptor`], and
/// [`crate::crypto::Pkcs12Encryptor`] using whichever crypto backend feature is
/// active (`openssl` or `nss`).
///
/// Use this instead of the `Openssl`-prefixed types when you want code that
/// compiles and works with either backend without `#[cfg]` guards at call sites.
pub struct DefaultCrypto;

// ── Pkcs12Decryptor ───────────────────────────────────────────────────────────

impl crate::crypto::Pkcs12Decryptor for DefaultCrypto {
    type Error = DefaultCryptoError;

    fn decrypt(
        &self,
        algorithm_der: &[u8],
        ciphertext: &[u8],
        password: &[u8],
    ) -> Result<Vec<u8>, DefaultCryptoError> {
        let (oid, _, _) = split_alg_id(algorithm_der, DefaultCryptoError::from)?;
        if oid.components() != ID_PBES2 {
            return Err(DefaultCryptoError::UnsupportedAlgorithm(format!(
                "unsupported PKCS#12 encryption OID: {:?}; only id-PBES2 is supported",
                oid.components()
            )));
        }
        decrypt_pbes2(algorithm_der, ciphertext, password)
    }
}

/// PBES2 decryption (RFC 8018 §6.2) using the active backend's PBKDF2 and
/// AES-CBC providers.
fn decrypt_pbes2(
    algorithm_der: &[u8],
    ciphertext: &[u8],
    password: &[u8],
) -> Result<Vec<u8>, DefaultCryptoError> {
    let (_oid, _, params_der) = split_alg_id(algorithm_der, DefaultCryptoError::from)?;
    let mut pdec = Decoder::new(params_der, Encoding::Der);
    let pbes2: Pbes2Params = pdec.decode()?;

    let (kdf_oid, _, kdf_params_der) = split_alg_id(
        pbes2.key_derivation_func.as_bytes(),
        DefaultCryptoError::from,
    )?;
    if kdf_oid.components() != ID_PBKDF2 {
        return Err(DefaultCryptoError::UnsupportedAlgorithm(format!(
            "unsupported PBES2 KDF OID: {:?}; only id-PBKDF2 is supported",
            kdf_oid.components()
        )));
    }

    let mut kp_dec = Decoder::new(kdf_params_der, Encoding::Der);
    let kdf_params: Pbkdf2Params = kp_dec.decode()?;

    // Default PRF when absent: HMAC-SHA-1 (RFC 8018 §5.2).
    let prf_alg = if let Some(prf_raw) = &kdf_params.prf {
        let (prf_oid, _, _) = split_alg_id(prf_raw.as_bytes(), DefaultCryptoError::from)?;
        oid_to_hmac_alg(prf_oid.components())?
    } else {
        "sha1"
    };

    let (enc_oid, _, enc_params_der) =
        split_alg_id(pbes2.encryption_scheme.as_bytes(), DefaultCryptoError::from)?;
    let (key_len, _) = oid_to_aes_params(enc_oid.components())?;
    let iv = decode_octet_string_content(enc_params_der)?;

    let salt = kdf_params.salt.as_bytes();
    let iter = kdf_params.iteration_count.as_u64().map_err(|_| {
        DefaultCryptoError::UnsupportedAlgorithm(
            "PBKDF2 iteration count is out of u64 range".into(),
        )
    })? as usize;

    let key = crate::default_pbkdf2_provider()
        .pbkdf2_hmac(prf_alg, password, salt, iter, key_len)
        .map_err(|e| DefaultCryptoError::Backend(e.to_string()))?;

    crate::default_block_cipher_provider()
        .aes_cbc_decrypt(&key, iv, ciphertext, true)
        .map_err(|e| DefaultCryptoError::Backend(e.to_string()))
}

// ── CmsDecryptor ──────────────────────────────────────────────────────────────

impl crate::crypto::CmsDecryptor for DefaultCrypto {
    type Error = DefaultCryptoError;

    fn decrypt(
        &self,
        algorithm_der: &[u8],
        ciphertext: &[u8],
        key: &[u8],
    ) -> Result<Vec<u8>, DefaultCryptoError> {
        let (oid, _, params_der) = split_alg_id(algorithm_der, DefaultCryptoError::from)?;
        let (expected_key_len, _) = oid_to_aes_params(oid.components())?;
        if key.len() != expected_key_len {
            return Err(DefaultCryptoError::UnsupportedAlgorithm(format!(
                "key length mismatch: expected {} bytes for {:?}, got {}",
                expected_key_len,
                oid.components(),
                key.len()
            )));
        }
        let iv = decode_octet_string_content(params_der)?;
        crate::default_block_cipher_provider()
            .aes_cbc_decrypt(key, iv, ciphertext, true)
            .map_err(|e| DefaultCryptoError::Backend(e.to_string()))
    }
}

// ── Encryptor ─────────────────────────────────────────────────────────────────

impl crate::crypto::Encryptor for DefaultCrypto {
    type Error = DefaultCryptoError;

    fn encrypt(
        &self,
        alg_oid: &[u32],
        plaintext: &[u8],
        key: &[u8],
    ) -> Result<(Vec<u8>, Vec<u8>), DefaultCryptoError> {
        let (expected_key_len, iv_len) = oid_to_aes_params(alg_oid)?;
        if key.len() != expected_key_len {
            return Err(DefaultCryptoError::UnsupportedAlgorithm(format!(
                "key length mismatch: expected {} bytes for {:?}, got {}",
                expected_key_len,
                alg_oid,
                key.len()
            )));
        }
        let mut iv = vec![0u8; iv_len];
        crate::default_secure_random()
            .rand_bytes(&mut iv)
            .map_err(|e| DefaultCryptoError::Backend(e.to_string()))?;
        let ciphertext = crate::default_block_cipher_provider()
            .aes_cbc_encrypt(key, &iv, plaintext, true)
            .map_err(|e| DefaultCryptoError::Backend(e.to_string()))?;
        let alg_id_der = build_aes_cbc_alg_id(alg_oid, &iv)?;
        Ok((alg_id_der, ciphertext))
    }
}

// ── CmsEncryptor ──────────────────────────────────────────────────────────────

impl crate::crypto::CmsEncryptor for DefaultCrypto {
    fn create_encrypted_data(
        &self,
        content_type_oid: &[u32],
        enc_alg_oid: &[u32],
        plaintext: &[u8],
        key: &[u8],
    ) -> Result<Vec<u8>, DefaultCryptoError> {
        use crate::cms_rfc5652_types::{EncryptedContentInfo, EncryptedData};
        use crate::crypto::Encryptor as _;
        use synta::{Integer, ObjectIdentifier, OctetStringRef};

        let (enc_alg_id_der, ciphertext) = self.encrypt(enc_alg_oid, plaintext, key)?;
        let content_type = ObjectIdentifier::new(content_type_oid).map_err(|_| {
            DefaultCryptoError::UnsupportedAlgorithm(format!(
                "invalid content-type OID: {:?}",
                content_type_oid
            ))
        })?;
        let content_encryption_algorithm: crate::AlgorithmIdentifier<'_> =
            Decoder::new(&enc_alg_id_der, Encoding::Der).decode()?;
        let ed = EncryptedData {
            version: Integer::from_i64(0),
            encrypted_content_info: EncryptedContentInfo {
                content_type,
                content_encryption_algorithm,
                encrypted_content: Some(OctetStringRef::new(&ciphertext)),
            },
            unprotected_attrs: None,
        };
        ed.to_der().map_err(DefaultCryptoError::from)
    }
}

// ── Pkcs12Encryptor ───────────────────────────────────────────────────────────

/// Build a DER-encoded PBES2 `AlgorithmIdentifier` for `EncryptedPrivateKeyInfo`.
fn build_pbes2_alg_id_der(
    kdf_salt: &[u8],
    iv: &[u8],
    iterations: u32,
    key_len: u32,
    cipher_oid: &[u32],
    prf_oid: &[u32],
) -> Result<Vec<u8>, DefaultCryptoError> {
    use crate::pkcs12_types::{Pbes2Params, Pbkdf2Params, ID_PBES2, ID_PBKDF2};
    use synta::traits::Decode;
    use synta::{Element, Null, ObjectIdentifier, OctetStringRef, RawDer};

    // PRF AlgorithmIdentifier { prfOid, NULL }
    let prf_alg_der = {
        let oid = ObjectIdentifier::new(prf_oid).map_err(|_| {
            DefaultCryptoError::UnsupportedAlgorithm("invalid PRF OID components".into())
        })?;
        crate::AlgorithmIdentifier {
            algorithm: oid,
            parameters: Some(Element::Null(Null)),
        }
        .to_der()?
    };

    // PBKDF2-params SEQUENCE
    let pbkdf2_params_der = Pbkdf2Params {
        salt: OctetStringRef::new(kdf_salt),
        iteration_count: synta::Integer::from(iterations),
        key_length: Some(synta::Integer::from(key_len)),
        prf: Some(RawDer(&prf_alg_der)),
    }
    .to_der()?;

    // PBKDF2 AlgorithmIdentifier { id-PBKDF2, PBKDF2-params }
    let kdf_alg_der = {
        let oid = ObjectIdentifier::new(ID_PBKDF2).map_err(|_| {
            DefaultCryptoError::UnsupportedAlgorithm("invalid id-PBKDF2 OID".into())
        })?;
        let mut dec = Decoder::new(&pbkdf2_params_der, Encoding::Der);
        let params_elem: Element<'_> = Element::decode(&mut dec)?;
        crate::AlgorithmIdentifier {
            algorithm: oid,
            parameters: Some(params_elem),
        }
        .to_der()?
    };

    // Cipher AlgorithmIdentifier { cipherOid, OCTET STRING(iv) }
    let enc_alg_der = build_aes_cbc_alg_id(cipher_oid, iv)?;

    // PBES2-params SEQUENCE
    let pbes2_params_der = Pbes2Params {
        key_derivation_func: RawDer(&kdf_alg_der),
        encryption_scheme: RawDer(&enc_alg_der),
    }
    .to_der()?;

    // Outer PBES2 AlgorithmIdentifier { id-PBES2, PBES2-params }
    let oid = ObjectIdentifier::new(ID_PBES2)
        .map_err(|_| DefaultCryptoError::UnsupportedAlgorithm("invalid id-PBES2 OID".into()))?;
    let mut dec = Decoder::new(&pbes2_params_der, Encoding::Der);
    let params_elem: Element<'_> = Element::decode(&mut dec)?;
    crate::AlgorithmIdentifier {
        algorithm: oid,
        parameters: Some(params_elem),
    }
    .to_der()
    .map_err(DefaultCryptoError::from)
}

impl crate::crypto::Pkcs12Encryptor for DefaultCrypto {
    type Error = DefaultCryptoError;

    fn encrypt(
        &self,
        plaintext: &[u8],
        password: &[u8],
    ) -> Result<(Vec<u8>, Vec<u8>), DefaultCryptoError> {
        // Default: PBKDF2-SHA256, AES-256-CBC, 600 000 iterations.
        const ITER: u32 = 600_000;
        const KEY_LEN: usize = 32; // AES-256
        const IV_LEN: usize = 16;

        let mut kdf_salt = vec![0u8; 16];
        let mut iv = vec![0u8; IV_LEN];
        crate::default_secure_random()
            .rand_bytes(&mut kdf_salt)
            .map_err(|e| DefaultCryptoError::Backend(e.to_string()))?;
        crate::default_secure_random()
            .rand_bytes(&mut iv)
            .map_err(|e| DefaultCryptoError::Backend(e.to_string()))?;

        let key = crate::default_pbkdf2_provider()
            .pbkdf2_hmac("sha256", password, &kdf_salt, ITER as usize, KEY_LEN)
            .map_err(|e| DefaultCryptoError::Backend(e.to_string()))?;

        let ciphertext = crate::default_block_cipher_provider()
            .aes_cbc_encrypt(&key, &iv, plaintext, true)
            .map_err(|e| DefaultCryptoError::Backend(e.to_string()))?;

        let alg_id_der = build_pbes2_alg_id_der(
            &kdf_salt,
            &iv,
            ITER,
            KEY_LEN as u32,
            ID_AES256_CBC,
            ID_HMAC_WITH_SHA256,
        )?;
        Ok((alg_id_der, ciphertext))
    }

    fn compute_mac(
        &self,
        auth_safe_content: &[u8],
        password: &[u8],
    ) -> Result<Vec<u8>, DefaultCryptoError> {
        use crate::pkcs12_types::{MacData, MacDigestInfo};
        use synta::{Element, Null, ObjectIdentifier, OctetStringRef};

        const MAC_ITER: u32 = 600_000;
        const MAC_KEY_LEN: usize = 32; // SHA-256 output

        // Generate random 8-byte MAC salt.
        let mut mac_salt = [0u8; 8];
        crate::default_secure_random()
            .rand_bytes(&mut mac_salt)
            .map_err(|e| DefaultCryptoError::Backend(e.to_string()))?;

        // Derive MAC key via PBKDF2-SHA256.
        let mac_key = crate::default_pbkdf2_provider()
            .pbkdf2_hmac(
                "sha256",
                password,
                &mac_salt,
                MAC_ITER as usize,
                MAC_KEY_LEN,
            )
            .map_err(|e| DefaultCryptoError::Backend(e.to_string()))?;

        // Compute HMAC-SHA256 over the AuthenticatedSafe bytes.
        let hmac_bytes = crate::default_hmac_provider()
            .hmac_compute("sha256", &mac_key, auth_safe_content)
            .map_err(|e| DefaultCryptoError::Backend(e.to_string()))?;

        // Build MacDigestInfo: { digestAlgorithm: { id-hmacWithSHA256, NULL }, digest }.
        let hmac_oid = ObjectIdentifier::new(ID_HMAC_WITH_SHA256).map_err(|_| {
            DefaultCryptoError::UnsupportedAlgorithm(
                "invalid id-hmacWithSHA256 OID components".into(),
            )
        })?;
        let dig_alg = crate::AlgorithmIdentifier {
            algorithm: hmac_oid,
            parameters: Some(Element::Null(Null)),
        };
        let mac_digest_info = MacDigestInfo {
            digest_algorithm: dig_alg,
            digest: OctetStringRef::new(&hmac_bytes),
        };

        // Build MacData: { mac, macSalt, iterations }.
        let mac_data = MacData {
            mac: mac_digest_info,
            mac_salt: OctetStringRef::new(&mac_salt),
            iterations: synta::Integer::from(MAC_ITER),
        };
        mac_data.to_der().map_err(DefaultCryptoError::from)
    }
}

// ── DefaultEnvelopedDataDecryptor ─────────────────────────────────────────────

/// Backend-agnostic [`crate::EnvelopedDataDecryptor`] using a PKCS#8 private key.
///
/// Stores the recipient's RSA private key as DER-encoded unencrypted PKCS#8
/// bytes and dispatches to the active backend for RSA CEK unwrap and
/// AES-CBC content decryption.
pub struct DefaultEnvelopedDataDecryptor {
    pkcs8_der: Vec<u8>,
}

impl DefaultEnvelopedDataDecryptor {
    /// Create a new decryptor from DER-encoded unencrypted PKCS#8 bytes.
    ///
    /// Returns `Err` if the buffer is empty or the encoded key is not RSA.
    pub fn new(pkcs8_der: &[u8]) -> Result<Self, DefaultCryptoError> {
        if pkcs8_der.is_empty() {
            return Err(DefaultCryptoError::UnsupportedAlgorithm(
                "empty PKCS#8 DER".into(),
            ));
        }
        let key_type = super::utils::key_type_from_pkcs8(pkcs8_der);
        if key_type != "rsa" {
            return Err(DefaultCryptoError::UnsupportedAlgorithm(format!(
                "EnvelopedData decryption requires an RSA private key, got '{}'",
                key_type
            )));
        }
        Ok(Self {
            pkcs8_der: pkcs8_der.to_vec(),
        })
    }
}

impl crate::crypto::EnvelopedDataDecryptor for DefaultEnvelopedDataDecryptor {
    type Error = DefaultCryptoError;

    fn decrypt_enveloped(
        &self,
        ed: &crate::cms_rfc5652_types::EnvelopedData<'_>,
    ) -> Result<Vec<u8>, DefaultCryptoError> {
        use crate::cms_rfc5652_types::KeyTransRecipientInfo;
        use crate::crypto::CmsDecryptor as _;
        use synta::tag::{TAG_SEQUENCE, TAG_SET};
        use synta::{Tag, TagClass};

        let priv_key = BackendPrivateKey::from_pkcs8_der_unchecked(self.pkcs8_der.clone());

        // RecipientInfos is stored as a raw DER SET TLV — iterate its elements.
        let ri_raw = ed.recipient_infos.as_bytes();
        let set_tag = Tag::universal_constructed(TAG_SET);
        let mut outer = Decoder::new(ri_raw, Encoding::Ber);
        let mut inner = outer.enter_constructed(set_tag)?;

        let mut cek: Option<Vec<u8>> = None;
        while !inner.is_empty() {
            // Capture the TLV of the current element before advancing.
            let before = inner.remaining();
            let elem_tag = inner.peek_tag()?;
            inner.read_tag()?;
            let elem_len = inner.read_length()?.definite()?;
            inner.read_bytes(elem_len)?;
            let after = inner.remaining();
            let elem_tlv = &before[..before.len() - after.len()];

            // Only try KTRI decoding on plain SEQUENCE elements.
            if elem_tag.class() != TagClass::Universal
                || elem_tag.number() != TAG_SEQUENCE
                || !elem_tag.is_constructed()
            {
                continue;
            }

            let ktri: KeyTransRecipientInfo<'_> =
                match Decoder::new(elem_tlv, Encoding::Ber).decode() {
                    Ok(k) => k,
                    Err(_) => continue,
                };

            let alg_oid = ktri.key_encryption_algorithm.algorithm.components();
            let enc_key_bytes = ktri.encrypted_key.as_bytes();

            let decrypted = if alg_oid == crate::oids::RSAES_OAEP {
                priv_key.rsa_oaep_decrypt(enc_key_bytes, "sha256")
            } else if alg_oid == crate::RSA_ENCRYPTION {
                priv_key.rsa_pkcs1v15_decrypt(enc_key_bytes)
            } else {
                continue;
            };

            if let Ok(unwrapped) = decrypted {
                cek = Some(unwrapped);
                break;
            }
        }

        let cek = cek.ok_or_else(|| {
            DefaultCryptoError::UnsupportedAlgorithm(
                "no KeyTransRecipientInfo could be decrypted with the given private key"
                    .to_string(),
            )
        })?;

        let alg_der = ed
            .encrypted_content_info
            .content_encryption_algorithm
            .to_der()?;
        let ciphertext = ed
            .encrypted_content_info
            .encrypted_content
            .as_ref()
            .ok_or_else(|| {
                DefaultCryptoError::UnsupportedAlgorithm(
                    "EnvelopedData has no encryptedContent field".into(),
                )
            })?
            .as_bytes();

        DefaultCrypto.decrypt(&alg_der, ciphertext, &cek)
    }
}

// ── Backend-agnostic EnvelopedData builder helpers ────────────────────────────

/// Build one `KeyTransRecipientInfo` SEQUENCE from a recipient certificate DER.
fn default_build_ktri(
    cert_der: &[u8],
    key_wrap: crate::crypto::KeyWrapAlgorithm,
    cek: &[u8],
) -> Result<Vec<u8>, DefaultCryptoError> {
    use crate::cms_2010_types::IssuerAndSerialNumber;
    use crate::cms_rfc5652_types::KeyTransRecipientInfo;
    use synta::{Integer, OctetStringRef, RawDer};

    // Parse the certificate with synta to extract SPKI bytes and issuer/serial.
    let synta_cert: crate::Certificate<'_> = Decoder::new(cert_der, Encoding::Der).decode()?;
    let cert_ranges = crate::cert_byte_ranges(cert_der).ok_or_else(|| {
        DefaultCryptoError::UnsupportedAlgorithm(
            "failed to locate SubjectPublicKeyInfo in certificate DER".into(),
        )
    })?;
    let spki_der = cert_der[cert_ranges.subject_public_key_info].to_vec();
    let serial_number: Integer = synta_cert.tbs_certificate.serial_number;
    let issuer: crate::Name<'_> =
        Decoder::new(synta_cert.tbs_certificate.issuer.as_bytes(), Encoding::Der).decode()?;

    // Encrypt the CEK under the recipient's public key.
    let pub_key = BackendPublicKey::from_spki_der(spki_der);
    let (encrypted_cek, key_enc_alg_der) = match key_wrap {
        crate::crypto::KeyWrapAlgorithm::RsaOaepSha256 => {
            let ct = pub_key
                .rsa_oaep_encrypt(cek, "sha256")
                .map_err(|e| DefaultCryptoError::Backend(e.to_string()))?;
            (ct, build_rsa_oaep_sha256_alg_id()?)
        }
        crate::crypto::KeyWrapAlgorithm::RsaPkcs1v15 => {
            let ct = pub_key
                .rsa_pkcs1v15_encrypt(cek)
                .map_err(|e| DefaultCryptoError::Backend(e.to_string()))?;
            (ct, build_rsa_pkcs1v15_alg_id()?)
        }
    };

    let isn_der = IssuerAndSerialNumber {
        issuer,
        serial_number,
    }
    .to_der()?;

    let key_encryption_algorithm: crate::AlgorithmIdentifier<'_> =
        Decoder::new(&key_enc_alg_der, Encoding::Der).decode()?;

    KeyTransRecipientInfo {
        version: Integer::from_i64(0),
        rid: RawDer(&isn_der),
        key_encryption_algorithm,
        encrypted_key: OctetStringRef::new(&encrypted_cek),
    }
    .to_der()
    .map_err(DefaultCryptoError::from)
}

/// Generate a fresh CEK, encrypt the plaintext, build one KTRI per recipient,
/// and return a pre-loaded [`crate::EnvelopedDataBuilder`].
///
/// This is the backend-agnostic equivalent of `prepare_enveloped_data` from
/// `openssl_backend`.  Works with both `openssl` and `nss` features.
pub fn default_prepare_enveloped_data(
    plaintext: &[u8],
    recipients: &[(&[u8], crate::crypto::KeyWrapAlgorithm)],
    content_enc_alg_oid: &[u32],
) -> Result<crate::EnvelopedDataBuilder, DefaultCryptoError> {
    use crate::crypto::Encryptor as _;

    if recipients.is_empty() {
        return Err(DefaultCryptoError::UnsupportedAlgorithm(
            "EnvelopedData requires at least one recipient".into(),
        ));
    }

    let (cek_len, _) = oid_to_aes_params(content_enc_alg_oid)?;
    let mut cek = vec![0u8; cek_len];
    crate::default_secure_random()
        .rand_bytes(&mut cek)
        .map_err(|e| DefaultCryptoError::Backend(e.to_string()))?;

    let (enc_alg_id_der, ciphertext) =
        DefaultCrypto.encrypt(content_enc_alg_oid, plaintext, &cek)?;

    let ktri_ders: Result<Vec<Vec<u8>>, DefaultCryptoError> = recipients
        .iter()
        .map(|(cert_der, key_wrap)| default_build_ktri(cert_der, *key_wrap, &cek))
        .collect();
    let ktri_ders = ktri_ders?;

    // Zeroize the CEK with volatile writes so the optimiser cannot elide them.
    for b in cek.iter_mut() {
        // SAFETY: `b` is a valid mutable reference; volatile write prevents elision.
        unsafe { std::ptr::write_volatile(b, 0) };
    }

    let mut builder = crate::EnvelopedDataBuilder::new(enc_alg_id_der, ciphertext);
    for ktri_der in ktri_ders {
        builder = builder.add_recipient_info(ktri_der);
    }
    Ok(builder)
}

/// Build a complete CMS `EnvelopedData` SEQUENCE DER using the active backend.
///
/// Backend-agnostic equivalent of `create_enveloped_data` from `openssl_backend`.
pub fn default_create_enveloped_data(
    plaintext: &[u8],
    recipients: &[(&[u8], crate::crypto::KeyWrapAlgorithm)],
    content_enc_alg_oid: &[u32],
) -> Result<Vec<u8>, DefaultCryptoError> {
    use crate::enveloped_data_builder::EnvelopedDataBuilderError;
    default_prepare_enveloped_data(plaintext, recipients, content_enc_alg_oid)?
        .build()
        .map_err(|e| match e {
            EnvelopedDataBuilderError::Encode(se) => DefaultCryptoError::Parse(se),
            EnvelopedDataBuilderError::InvalidOid(s) => {
                DefaultCryptoError::UnsupportedAlgorithm(format!("invalid OID: {s}"))
            }
            EnvelopedDataBuilderError::NoRecipients => DefaultCryptoError::UnsupportedAlgorithm(
                "EnvelopedData requires at least one recipient".into(),
            ),
        })
}