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
//! RSA OAEP/PKCS1 key encryption/decryption + CMS `EnvelopedData` builder (RFC 5652 §6).

use crate::crypto::{KeyDecryptor, KeyEncryptor, KeyWrapAlgorithm};

use super::cms::{oid_to_cipher, OpensslDecryptorError, OpensslEncryptorError};
use super::OpensslKeyError;

use native_ossl::params::ParamBuilder;
use native_ossl::pkey::{Pkey, PkeyDecryptCtx, PkeyEncryptCtx, Private, Public};
use native_ossl::rand::Rand;

fn hash_alg_name(alg: &str) -> Result<&'static std::ffi::CStr, OpensslKeyError> {
    match alg {
        "sha1" => Ok(c"SHA1"),
        "sha224" => Ok(c"SHA2-224"),
        "sha256" => Ok(c"SHA2-256"),
        "sha384" => Ok(c"SHA2-384"),
        "sha512" => Ok(c"SHA2-512"),
        other => Err(OpensslKeyError(format!(
            "unsupported hash algorithm: {other}; \
             expected sha1, sha224, sha256, sha384, or sha512"
        ))),
    }
}

// ── Private RSA crypto helpers (take stored Pkey directly) ───────────────────

pub(super) fn rsa_oaep_encrypt_with_key(
    key: &Pkey<Public>,
    plaintext: &[u8],
    hash_alg: &str,
) -> Result<Vec<u8>, OpensslKeyError> {
    let hash_name = hash_alg_name(hash_alg)?;
    let params = ParamBuilder::new()?
        .push_utf8_string(c"pad-mode", c"oaep")?
        .push_utf8_string(c"oaep-digest", hash_name)?
        .push_utf8_string(c"mgf1-digest", hash_name)?
        .build()?;
    let mut ctx = PkeyEncryptCtx::new(key, Some(&params))?;
    let outlen = ctx.encrypt_len(plaintext.len())?;
    let mut out = vec![0u8; outlen];
    let n = ctx.encrypt(plaintext, &mut out)?;
    out.truncate(n);
    Ok(out)
}

pub(super) fn rsa_pkcs1_encrypt_with_key(
    key: &Pkey<Public>,
    plaintext: &[u8],
) -> Result<Vec<u8>, OpensslKeyError> {
    let params = ParamBuilder::new()?
        .push_utf8_string(c"pad-mode", c"pkcs1")?
        .build()?;
    let mut ctx = PkeyEncryptCtx::new(key, Some(&params))?;
    let outlen = ctx.encrypt_len(plaintext.len())?;
    let mut out = vec![0u8; outlen];
    let n = ctx.encrypt(plaintext, &mut out)?;
    out.truncate(n);
    Ok(out)
}

pub(super) fn rsa_oaep_decrypt_with_key(
    key: &Pkey<Private>,
    ciphertext: &[u8],
    hash_alg: &str,
) -> Result<Vec<u8>, OpensslKeyError> {
    let hash_name = hash_alg_name(hash_alg)?;
    let params = ParamBuilder::new()?
        .push_utf8_string(c"pad-mode", c"oaep")?
        .push_utf8_string(c"oaep-digest", hash_name)?
        .push_utf8_string(c"mgf1-digest", hash_name)?
        .build()?;
    let mut ctx = PkeyDecryptCtx::new(key, Some(&params))?;
    let mut out = vec![0u8; ciphertext.len()];
    let n = ctx.decrypt(ciphertext, &mut out)?;
    out.truncate(n);
    Ok(out)
}

pub(super) fn rsa_pkcs1_decrypt_with_key(
    key: &Pkey<Private>,
    ciphertext: &[u8],
) -> Result<Vec<u8>, OpensslKeyError> {
    let params = ParamBuilder::new()?
        .push_utf8_string(c"pad-mode", c"pkcs1")?
        .build()?;
    let mut ctx = PkeyDecryptCtx::new(key, Some(&params))?;
    let mut out = vec![0u8; ciphertext.len()];
    let n = ctx.decrypt(ciphertext, &mut out)?;
    out.truncate(n);
    Ok(out)
}

/// OpenSSL-backed RSA-OAEP [`KeyEncryptor`].
///
/// Encrypts data under an RSA public key using OAEP padding (RFC 8017).
/// Prefer this over [`OpensslRsaPkcs1Encryptor`] for new protocols.
///
/// ```rust,ignore
/// use synta_certificate::OpensslRsaOaepEncryptor;
///
/// let enc = OpensslRsaOaepEncryptor::new(spki_der, "sha256")?;
/// let ciphertext = enc.encrypt_key(&cek)?;
/// ```
pub struct OpensslRsaOaepEncryptor {
    key: Pkey<Public>,
    hash_algorithm: String,
}

impl OpensslRsaOaepEncryptor {
    /// Create a new OAEP encryptor.
    ///
    /// `spki_der` must be a DER-encoded `SubjectPublicKeyInfo` containing an
    /// RSA public key.  Returns `Err` if the key cannot be parsed or is not RSA.
    pub fn new(spki_der: &[u8], hash_algorithm: &str) -> Result<Self, OpensslKeyError> {
        let key = Pkey::<Public>::from_der(spki_der)
            .map_err(|e| OpensslKeyError(format!("failed to load public key: {e}")))?;
        if !key.is_a(c"RSA") {
            return Err(OpensslKeyError(
                "RSA-OAEP encryption requires an RSA public key".to_string(),
            ));
        }
        Ok(Self {
            key,
            hash_algorithm: hash_algorithm.to_owned(),
        })
    }
}

impl KeyEncryptor for OpensslRsaOaepEncryptor {
    type Error = OpensslKeyError;

    fn encrypt_key(&self, plaintext: &[u8]) -> Result<Vec<u8>, OpensslKeyError> {
        rsa_oaep_encrypt_with_key(&self.key, plaintext, &self.hash_algorithm)
    }
}

/// OpenSSL-backed RSA-OAEP [`KeyDecryptor`].
///
/// Decrypts data encrypted with RSA-OAEP padding (RFC 8017).
///
/// ```rust,ignore
/// use synta_certificate::OpensslRsaOaepDecryptor;
///
/// let dec = OpensslRsaOaepDecryptor::new(pkcs8_der, "sha256")?;
/// let cek = dec.decrypt_key(&wrapped_cek)?;
/// ```
pub struct OpensslRsaOaepDecryptor {
    key: Pkey<Private>,
    hash_algorithm: String,
}

impl OpensslRsaOaepDecryptor {
    /// Create a new OAEP decryptor.
    ///
    /// `pkcs8_der` must be DER-encoded unencrypted PKCS\#8 bytes for an RSA
    /// private key.  Returns `Err` if the key cannot be parsed or is not RSA.
    pub fn new(pkcs8_der: &[u8], hash_algorithm: &str) -> Result<Self, OpensslKeyError> {
        let key = Pkey::<Private>::from_der(pkcs8_der)
            .map_err(|e| OpensslKeyError(format!("failed to load private key: {e}")))?;
        if !key.is_a(c"RSA") {
            return Err(OpensslKeyError(
                "RSA-OAEP decryption requires an RSA private key".to_string(),
            ));
        }
        Ok(Self {
            key,
            hash_algorithm: hash_algorithm.to_owned(),
        })
    }
}

impl KeyDecryptor for OpensslRsaOaepDecryptor {
    type Error = OpensslKeyError;

    fn decrypt_key(&self, ciphertext: &[u8]) -> Result<Vec<u8>, OpensslKeyError> {
        rsa_oaep_decrypt_with_key(&self.key, ciphertext, &self.hash_algorithm)
    }
}

/// OpenSSL-backed RSA PKCS#1 v1.5 [`KeyEncryptor`].
///
/// Encrypts data under an RSA public key using PKCS#1 v1.5 padding.
/// Prefer [`OpensslRsaOaepEncryptor`] for new protocols; this exists for
/// interoperability with legacy systems.
///
/// ```rust,ignore
/// use synta_certificate::OpensslRsaPkcs1Encryptor;
///
/// let enc = OpensslRsaPkcs1Encryptor::new(spki_der)?;
/// let ciphertext = enc.encrypt_key(&cek)?;
/// ```
pub struct OpensslRsaPkcs1Encryptor {
    key: Pkey<Public>,
}

impl OpensslRsaPkcs1Encryptor {
    /// Create a new PKCS\#1 v1.5 encryptor.
    ///
    /// `spki_der` must be a DER-encoded `SubjectPublicKeyInfo` containing an
    /// RSA public key.  Returns `Err` if the key cannot be parsed or is not RSA.
    pub fn new(spki_der: &[u8]) -> Result<Self, OpensslKeyError> {
        let key = Pkey::<Public>::from_der(spki_der)
            .map_err(|e| OpensslKeyError(format!("failed to load public key: {e}")))?;
        if !key.is_a(c"RSA") {
            return Err(OpensslKeyError(
                "RSA PKCS#1 v1.5 encryption requires an RSA public key".to_string(),
            ));
        }
        Ok(Self { key })
    }
}

impl KeyEncryptor for OpensslRsaPkcs1Encryptor {
    type Error = OpensslKeyError;

    fn encrypt_key(&self, plaintext: &[u8]) -> Result<Vec<u8>, OpensslKeyError> {
        rsa_pkcs1_encrypt_with_key(&self.key, plaintext)
    }
}

/// OpenSSL-backed RSA PKCS#1 v1.5 [`KeyDecryptor`].
///
/// Decrypts data encrypted with RSA PKCS#1 v1.5 padding.
/// Prefer [`OpensslRsaOaepDecryptor`] for new protocols; this exists for
/// interoperability with legacy systems.
///
/// ```rust,ignore
/// use synta_certificate::OpensslRsaPkcs1Decryptor;
///
/// let dec = OpensslRsaPkcs1Decryptor::new(pkcs8_der)?;
/// let cek = dec.decrypt_key(&wrapped_cek)?;
/// ```
pub struct OpensslRsaPkcs1Decryptor {
    key: Pkey<Private>,
}

impl OpensslRsaPkcs1Decryptor {
    /// Create a new PKCS\#1 v1.5 decryptor.
    ///
    /// `pkcs8_der` must be DER-encoded unencrypted PKCS\#8 bytes for an RSA
    /// private key.  Returns `Err` if the key cannot be parsed or is not RSA.
    pub fn new(pkcs8_der: &[u8]) -> Result<Self, OpensslKeyError> {
        let key = Pkey::<Private>::from_der(pkcs8_der)
            .map_err(|e| OpensslKeyError(format!("failed to load private key: {e}")))?;
        if !key.is_a(c"RSA") {
            return Err(OpensslKeyError(
                "RSA PKCS#1 v1.5 decryption requires an RSA private key".to_string(),
            ));
        }
        Ok(Self { key })
    }
}

impl KeyDecryptor for OpensslRsaPkcs1Decryptor {
    type Error = OpensslKeyError;

    fn decrypt_key(&self, ciphertext: &[u8]) -> Result<Vec<u8>, OpensslKeyError> {
        rsa_pkcs1_decrypt_with_key(&self.key, ciphertext)
    }
}

// ── CMS EnvelopedData builder ─────────────────────────────────────────────────

impl From<OpensslKeyError> for OpensslEncryptorError {
    fn from(e: OpensslKeyError) -> Self {
        OpensslEncryptorError::UnsupportedAlgorithm(e.0)
    }
}

/// Build a DER-encoded `AlgorithmIdentifier` for `id-RSAES-OAEP` with
/// SHA-256 hash and MGF1-SHA-256 mask generation (RFC 8017 §A.2.1).
///
/// Uses the generated `RsaesOaepParams` and `AlgorithmIdentifier` types so the
/// encoding is always consistent with the rest of the codebase.
fn build_rsa_oaep_sha256_alg_id() -> Result<Vec<u8>, OpensslEncryptorError> {
    use crate::pkcs1_types::{RsaesOaepParams, ID_MGF1, ID_RSAES_OAEP};
    use crate::AlgorithmIdentifier;
    use synta::{Decoder, Element, Encoding, ObjectIdentifier};

    // Step 1: SHA-256 AlgorithmIdentifier with no params (RFC 4055 §2.1).
    let sha256_alg_der = {
        let oid = ObjectIdentifier::new(crate::ID_SHA256).map_err(|_| {
            OpensslEncryptorError::UnsupportedAlgorithm("invalid SHA-256 OID".into())
        })?;
        AlgorithmIdentifier {
            algorithm: oid,
            parameters: None,
        }
        .to_der()?
    };

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

    // Step 3: RsaesOaepParams { [0] sha256, [1] mgf1+sha256 }.
    let oaep_params_der = {
        let hash_alg: AlgorithmIdentifier<'_> =
            Decoder::new(&sha256_alg_der, Encoding::Der).decode()?;
        let mask_gen: 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()?
    };

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

/// Build a DER-encoded `AlgorithmIdentifier` for `rsaEncryption` (1.2.840.113549.1.1.1)
/// with a NULL parameters field, as used for PKCS#1 v1.5 key transport.
fn build_rsa_pkcs1v15_alg_id() -> Result<Vec<u8>, OpensslEncryptorError> {
    use crate::AlgorithmIdentifier;
    use synta::{Element, Null, ObjectIdentifier};

    let oid = ObjectIdentifier::new(crate::RSA_ENCRYPTION).map_err(|_| {
        OpensslEncryptorError::UnsupportedAlgorithm("invalid rsaEncryption OID".into())
    })?;
    Ok(AlgorithmIdentifier {
        algorithm: oid,
        parameters: Some(Element::Null(Null)),
    }
    .to_der()?)
}

/// Build one `KeyTransRecipientInfo` SEQUENCE (RFC 5652 §6.2.1) for a
/// single recipient.
///
/// Returns the DER-encoded `KeyTransRecipientInfo` SEQUENCE.
fn build_ktri(
    cert_der: &[u8],
    key_wrap: KeyWrapAlgorithm,
    cek: &[u8],
) -> Result<Vec<u8>, OpensslEncryptorError> {
    use crate::cms_2010_types::IssuerAndSerialNumber;
    use crate::cms_rfc5652_types::KeyTransRecipientInfo;
    use synta::{Decoder, Encoding, Integer, OctetStringRef, RawDer};

    // Decode recipient certificate via synta — provides SPKI, issuer, and serial.
    let synta_cert: crate::Certificate<'_> = Decoder::new(cert_der, Encoding::Der).decode()?;
    let spki_der: Vec<u8> = synta_cert
        .tbs_certificate
        .subject_public_key_info
        .to_der()?;

    // Build key-encryption AlgorithmIdentifier DER.
    let key_enc_alg_der = match key_wrap {
        KeyWrapAlgorithm::RsaOaepSha256 => build_rsa_oaep_sha256_alg_id()?,
        KeyWrapAlgorithm::RsaPkcs1v15 => build_rsa_pkcs1v15_alg_id()?,
    };

    // Encrypt CEK under recipient's public key.
    let encrypted_cek: Vec<u8> = match key_wrap {
        KeyWrapAlgorithm::RsaOaepSha256 => {
            OpensslRsaOaepEncryptor::new(&spki_der, "sha256")?.encrypt_key(cek)?
        }
        KeyWrapAlgorithm::RsaPkcs1v15 => {
            OpensslRsaPkcs1Encryptor::new(&spki_der)?.encrypt_key(cek)?
        }
    };

    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()?;

    // Encode IssuerAndSerialNumber — this IS the RecipientIdentifier bytes
    // (issuerAndSerialNumber CHOICE; the SEQUENCE tag identifies the choice).
    let isn_der = IssuerAndSerialNumber {
        issuer,
        serial_number,
    }
    .to_der()?;

    // Decode key-encryption AlgorithmIdentifier from its DER bytes.
    let key_encryption_algorithm: crate::AlgorithmIdentifier<'_> =
        Decoder::new(&key_enc_alg_der, Encoding::Der).decode()?;

    // Build and encode KeyTransRecipientInfo using the generated struct.
    Ok(KeyTransRecipientInfo {
        version: Integer::from_i64(0),
        rid: RawDer(&isn_der),
        key_encryption_algorithm,
        encrypted_key: OctetStringRef::new(&encrypted_cek),
    }
    .to_der()?)
}

/// Generate a fresh CEK, encrypt the plaintext, build one
/// `KeyTransRecipientInfo` per recipient, and return a pre-loaded
/// [`crate::EnvelopedDataBuilder`].
///
/// This is the two-step alternative to [`create_enveloped_data`]: all
/// cryptographic work is done here, but the caller can still attach
/// `OriginatorInfo` certificates/CRLs via
/// [`EnvelopedDataBuilder::originator_cert`](crate::EnvelopedDataBuilder::originator_cert) /
/// [`originator_crl`](crate::EnvelopedDataBuilder::originator_crl), or set
/// `UnprotectedAttributes` via
/// [`unprotected_attrs`](crate::EnvelopedDataBuilder::unprotected_attrs),
/// before calling `.build()`.
///
/// # Parameters
///
/// - `plaintext`: the content bytes to encrypt.
/// - `recipients`: slice of `(cert_der, KeyWrapAlgorithm)` pairs — must be
///   non-empty.  Each `cert_der` is a DER-encoded X.509 `Certificate`
///   SEQUENCE; the public key and `IssuerAndSerialNumber` are extracted from
///   it.  All recipients must have RSA public keys.
/// - `content_enc_alg_oid`: OID of the content-encryption algorithm
///   (e.g. `ID_AES256_CBC`).  Must be an AES-CBC variant recognised by
///   [`super::cms::OpensslEncryptor`].
///
/// # Errors
///
/// Returns [`OpensslEncryptorError`] if `recipients` is empty, if the
/// content-encryption OID is unsupported, if any certificate cannot be
/// parsed, or if any OpenSSL operation fails.
pub fn prepare_enveloped_data(
    plaintext: &[u8],
    recipients: &[(&[u8], KeyWrapAlgorithm)],
    content_enc_alg_oid: &[u32],
) -> Result<crate::EnvelopedDataBuilder, OpensslEncryptorError> {
    use super::cms::OpensslEncryptor;
    use crate::crypto::Encryptor as _;

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

    // 1. Determine CEK size and generate a fresh random CEK.
    let (_, cek_len) = oid_to_cipher(content_enc_alg_oid)
        .map_err(|e| OpensslEncryptorError::UnsupportedAlgorithm(e.to_string()))?;
    let mut cek = vec![0u8; cek_len];
    Rand::fill(&mut cek)?;

    // 2. Encrypt plaintext under the CEK.
    let (enc_alg_id_der, ciphertext) =
        OpensslEncryptor.encrypt(content_enc_alg_oid, plaintext, &cek)?;

    // 3. Build one KeyTransRecipientInfo per recipient (as DER bytes).
    let ktri_ders: Result<Vec<Vec<u8>>, _> = recipients
        .iter()
        .map(|(cert_der, key_wrap)| build_ktri(cert_der, *key_wrap, &cek))
        .collect();
    let ktri_ders = ktri_ders?;

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

    // 4. Populate the backend-agnostic builder with the pre-computed DER pieces.
    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 (RFC 5652 §6) with one or
/// more `KeyTransRecipientInfo` recipients and return the DER bytes.
///
/// A single content-encryption key (CEK) is generated at random, the
/// plaintext is encrypted under it, and the CEK is independently wrapped
/// for each recipient.  Each recipient entry is a `(cert_der,
/// KeyWrapAlgorithm)` pair: `cert_der` is the DER-encoded X.509
/// `Certificate` SEQUENCE; the public key and `IssuerAndSerialNumber` are
/// extracted from it.  All recipients must have RSA public keys.
///
/// To attach `OriginatorInfo` or `UnprotectedAttributes` before assembly,
/// use [`prepare_enveloped_data`] instead and call methods on the returned
/// builder before invoking `.build()`.
///
/// # Parameters
///
/// - `plaintext`: the content bytes to encrypt.
/// - `recipients`: slice of `(cert_der, KeyWrapAlgorithm)` pairs — must be
///   non-empty.
/// - `content_enc_alg_oid`: OID of the content-encryption algorithm
///   (e.g. `ID_AES256_CBC`).  Must be an AES-CBC variant recognised by
///   [`super::cms::OpensslEncryptor`].
///
/// # Returns
///
/// The DER-encoded `EnvelopedData` SEQUENCE.  To produce a complete CMS
/// message, wrap the result in a `ContentInfo` with OID
/// `id-envelopedData` (1.2.840.113549.1.7.3).
///
/// # Errors
///
/// Returns [`OpensslEncryptorError`] if `recipients` is empty, if the
/// content-encryption OID is unsupported, if any certificate cannot be
/// parsed, or if any OpenSSL or ASN.1 encoding operation fails.
pub fn create_enveloped_data(
    plaintext: &[u8],
    recipients: &[(&[u8], KeyWrapAlgorithm)],
    content_enc_alg_oid: &[u32],
) -> Result<Vec<u8>, OpensslEncryptorError> {
    use crate::enveloped_data_builder::EnvelopedDataBuilderError;

    prepare_enveloped_data(plaintext, recipients, content_enc_alg_oid)?
        .build()
        .map_err(|e| match e {
            EnvelopedDataBuilderError::Encode(se) => OpensslEncryptorError::Encode(se),
            EnvelopedDataBuilderError::InvalidOid(s) => {
                OpensslEncryptorError::UnsupportedAlgorithm(format!("invalid OID: {s}"))
            }
            EnvelopedDataBuilderError::NoRecipients => OpensslEncryptorError::UnsupportedAlgorithm(
                "EnvelopedData requires at least one recipient".into(),
            ),
        })
}

// ── OpensslEnvelopedDataDecryptor ─────────────────────────────────────────────

/// OpenSSL-backed [`crate::EnvelopedDataDecryptor`] using a PKCS\#8 private key.
///
/// Loads the recipient's RSA private key once at construction time from
/// DER-encoded unencrypted PKCS\#8 (`OneAsymmetricKey`) bytes.  Iterates the
/// `RecipientInfos` SET looking for a `KeyTransRecipientInfo` whose encrypted
/// CEK can be unwrapped with the stored key, then decrypts the content.
///
/// ```rust,ignore
/// use synta_certificate::{OpensslEnvelopedDataDecryptor, EnvelopedDataDecryptor as _};
///
/// let dec = OpensslEnvelopedDataDecryptor::new(&pkcs8_der)?;
/// let plaintext = dec.decrypt_enveloped(&enveloped_data)?;
/// ```
pub struct OpensslEnvelopedDataDecryptor {
    key: Pkey<Private>,
}

impl OpensslEnvelopedDataDecryptor {
    /// Create a new decryptor by loading the private key from PKCS\#8 DER bytes.
    ///
    /// Returns `Err` if the key cannot be parsed or is not an RSA key.
    pub fn new(pkcs8_der: &[u8]) -> Result<Self, OpensslKeyError> {
        let key = Pkey::<Private>::from_der(pkcs8_der)
            .map_err(|e| OpensslKeyError(format!("failed to load private key: {e}")))?;
        if !key.is_a(c"RSA") {
            return Err(OpensslKeyError(
                "EnvelopedData decryption requires an RSA private key".to_string(),
            ));
        }
        Ok(Self { key })
    }
}

impl crate::EnvelopedDataDecryptor for OpensslEnvelopedDataDecryptor {
    type Error = OpensslEncryptorError;

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

        // RecipientInfos<'a> is stored as RawDer — the full SET TLV bytes.
        // Iterate the SET contents looking for KeyTransRecipientInfo entries.
        let ri_raw = ed.recipient_infos.as_bytes();
        let set_tag = Tag::universal_constructed(TAG_SET);
        let mut outer = synta::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 full 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 attempt KTRI decoding for plain SEQUENCE elements (tag 0x30).
            if elem_tag.class() != TagClass::Universal
                || elem_tag.number() != TAG_SEQUENCE
                || !elem_tag.is_constructed()
            {
                continue;
            }

            let ktri: KeyTransRecipientInfo<'_> =
                match synta::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();

            // Use the pre-loaded key directly — no re-parsing on each recipient.
            let decrypted: Result<Vec<u8>, OpensslKeyError> = if alg_oid == crate::oids::RSAES_OAEP
            {
                rsa_oaep_decrypt_with_key(&self.key, enc_key_bytes, "sha256")
            } else if alg_oid == crate::RSA_ENCRYPTION {
                rsa_pkcs1_decrypt_with_key(&self.key, enc_key_bytes)
            } else {
                continue;
            };

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

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

        // Encode the content-encryption AlgorithmIdentifier as DER.
        let alg_der = ed
            .encrypted_content_info
            .content_encryption_algorithm
            .to_der()?;

        // Decrypt the encrypted content using the recovered CEK.
        let ciphertext = ed
            .encrypted_content_info
            .encrypted_content
            .as_ref()
            .ok_or_else(|| {
                OpensslEncryptorError::UnsupportedAlgorithm(
                    "EnvelopedData has no encryptedContent field".to_string(),
                )
            })?
            .as_bytes();

        use super::cms::OpensslDecryptor;
        crate::crypto::CmsDecryptor::decrypt(&OpensslDecryptor, &alg_der, ciphertext, &cek).map_err(
            |e| match e {
                OpensslDecryptorError::Parse(se) => OpensslEncryptorError::Encode(se),
                OpensslDecryptorError::UnsupportedAlgorithm(s) => {
                    OpensslEncryptorError::UnsupportedAlgorithm(s)
                }
                OpensslDecryptorError::Openssl(e) => OpensslEncryptorError::Openssl(e),
            },
        )
    }
}