synta-python 0.2.3

Python extension module for the 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
//! Python bindings for generic public and private key operations.
//!
//! Exposes [`PyPublicKey`] and [`PyPrivateKey`] as pyo3 classes supporting
//! RSA, EC, EdDSA, and DSA keys via the `synta-certificate` backend traits.
//! No direct `openssl::*` imports are used here.

use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::PyBytes;
use synta_certificate::{BackendPrivateKey, BackendPublicKey, PrivateKey};

// ── PublicKey ─────────────────────────────────────────────────────────────────

/// An asymmetric public key.
///
/// Supports RSA, EC (P-256, P-384, P-521), Ed25519, Ed448, and DSA keys.
/// Load from PEM or SubjectPublicKeyInfo DER; serialize back to PEM or DER.
/// RSA keys can encrypt data with OAEP or PKCS\#1 v1.5 padding.
///
/// ```python,ignore
/// import synta
///
/// # Load an RSA public key from a PEM file:
/// with open("rsa_pub.pem", "rb") as f:
///     pub = synta.PublicKey.from_pem(f.read())
/// print(pub.key_type)   # "rsa"
/// print(pub.key_size)   # e.g. 2048
///
/// # Encrypt with OAEP (SHA-256):
/// ct = pub.rsa_oaep_encrypt(b"secret", "sha256")
///
/// # Load an EC public key from SPKI DER:
/// ec_pub = synta.PublicKey.from_der(spki_der)
/// print(ec_pub.curve_name)  # "P-256"
/// ```
#[pyclass(frozen, name = "PublicKey")]
pub struct PyPublicKey {
    pub(crate) inner: BackendPublicKey,
}

#[pymethods]
impl PyPublicKey {
    /// Load a public key from PEM-encoded SubjectPublicKeyInfo data.
    ///
    /// Supports RSA, EC (P-256, P-384, P-521), Ed25519, Ed448, and DSA keys.
    ///
    /// ```python,ignore
    /// with open("pubkey.pem", "rb") as f:
    ///     pub = synta.PublicKey.from_pem(f.read())
    /// ```
    #[staticmethod]
    fn from_pem(data: &[u8]) -> PyResult<Self> {
        let inner =
            BackendPublicKey::from_pem(data).map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(Self { inner })
    }

    /// Construct an RSA public key from raw big-endian modulus *n* and public-exponent *e* bytes.
    ///
    /// This is the inverse of the :attr:`modulus` and :attr:`public_exponent` getters.
    /// Raises :exc:`ValueError` if the inputs do not encode a valid RSA key.
    ///
    /// ```python,ignore
    /// # n and e are big-endian bytes (e.g. extracted from a PKCS#11 token)
    /// pub = synta.PublicKey.from_rsa_components(n, e)
    /// assert pub.key_type == "rsa"
    /// ```
    #[staticmethod]
    fn from_rsa_components(n: &[u8], e: &[u8]) -> PyResult<Self> {
        let inner = BackendPublicKey::from_rsa_components(n, e)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(Self { inner })
    }

    /// Construct an EC public key from affine coordinates *x* and *y* (big-endian
    /// bytes) and a NIST curve name (``"P-256"``, ``"P-384"``, or ``"P-521"``).
    ///
    /// This is the inverse of the :attr:`x`, :attr:`y`, and :attr:`curve_name` getters.
    /// Raises :exc:`ValueError` for unknown curve names or invalid coordinates.
    ///
    /// ```python,ignore
    /// pub = synta.PublicKey.from_ec_components(x_bytes, y_bytes, "P-256")
    /// assert pub.key_type == "ec"
    /// ```
    #[staticmethod]
    fn from_ec_components(x: &[u8], y: &[u8], curve: &str) -> PyResult<Self> {
        let inner = BackendPublicKey::from_ec_components(x, y, curve)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(Self { inner })
    }

    /// Load a public key from a DER-encoded SubjectPublicKeyInfo structure.
    ///
    /// ```python,ignore
    /// with open("pubkey.der", "rb") as f:
    ///     pub = synta.PublicKey.from_der(f.read())
    /// ```
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let inner =
            BackendPublicKey::from_der(data).map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(Self { inner })
    }

    /// Serialize this public key to PEM-encoded SubjectPublicKeyInfo.
    ///
    /// ```python,ignore
    /// pem = pub.to_pem()
    /// open("pubkey.pem", "wb").write(pem)
    /// ```
    fn to_pem<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        let pem = self
            .inner
            .to_pem()
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(PyBytes::new(py, &pem))
    }

    /// Serialize this public key to DER-encoded SubjectPublicKeyInfo.
    ///
    /// ```python,ignore
    /// der = pub.to_der()
    /// open("pubkey.der", "wb").write(der)
    /// ```
    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        let der = self
            .inner
            .to_der()
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(PyBytes::new(py, &der))
    }

    /// The key algorithm as a lowercase string.
    ///
    /// Returns one of ``"rsa"``, ``"ec"``, ``"ed25519"``, ``"ed448"``,
    /// ``"dsa"``, or ``"unknown"``.
    #[getter]
    fn key_type(&self) -> &'static str {
        self.inner.key_type()
    }

    /// The key size in bits, or ``None`` for EdDSA keys.
    ///
    /// For RSA this is the modulus bit-length; for EC this is the field
    /// bit-length.  Returns ``None`` for Ed25519 and Ed448.
    #[getter]
    fn key_size(&self) -> Option<i64> {
        self.inner.key_bit_size()
    }

    /// The RSA modulus ``n`` as big-endian bytes, or ``None`` for non-RSA keys.
    #[getter]
    fn modulus<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyBytes>>> {
        match self
            .inner
            .rsa_modulus()
            .map_err(|e| PyValueError::new_err(format!("{e}")))?
        {
            Some(n) => Ok(Some(PyBytes::new(py, &n))),
            None => Ok(None),
        }
    }

    /// The RSA public exponent ``e`` as big-endian bytes, or ``None`` for
    /// non-RSA keys.
    ///
    /// The most common value is ``b'\x01\x00\x01'`` (65537).
    #[getter]
    fn public_exponent<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyBytes>>> {
        match self
            .inner
            .rsa_public_exponent()
            .map_err(|e| PyValueError::new_err(format!("{e}")))?
        {
            Some(e) => Ok(Some(PyBytes::new(py, &e))),
            None => Ok(None),
        }
    }

    /// The NIST curve name for EC keys, or ``None`` for non-EC keys.
    ///
    /// Returns ``"P-256"``, ``"P-384"``, ``"P-521"``, or ``"unknown"`` for
    /// EC keys on other curves.
    #[getter]
    fn curve_name(&self) -> PyResult<Option<&'static str>> {
        self.inner
            .ec_curve_name()
            .map_err(|e| PyValueError::new_err(format!("{e}")))
    }

    /// The affine X coordinate of the EC public key as big-endian bytes, or
    /// ``None`` for non-EC keys.
    #[getter]
    fn x<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyBytes>>> {
        match self
            .inner
            .ec_affine_coordinates()
            .map_err(|e| PyValueError::new_err(format!("{e}")))?
        {
            Some((xv, _)) => Ok(Some(PyBytes::new(py, &xv))),
            None => Ok(None),
        }
    }

    /// The affine Y coordinate of the EC public key as big-endian bytes, or
    /// ``None`` for non-EC keys.
    #[getter]
    fn y<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyBytes>>> {
        match self
            .inner
            .ec_affine_coordinates()
            .map_err(|e| PyValueError::new_err(format!("{e}")))?
        {
            Some((_, yv)) => Ok(Some(PyBytes::new(py, &yv))),
            None => Ok(None),
        }
    }

    /// Encrypt ``plaintext`` with RSA-OAEP using the specified hash algorithm.
    ///
    /// ``hash_algorithm`` must be one of ``"sha1"``, ``"sha224"``,
    /// ``"sha256"``, ``"sha384"``, or ``"sha512"``.
    ///
    /// Raises :exc:`ValueError` if this key is not an RSA key.
    ///
    /// ```python,ignore
    /// ct = pub.rsa_oaep_encrypt(b"secret data", "sha256")
    /// ```
    #[pyo3(signature = (plaintext, hash_algorithm = "sha256"))]
    fn rsa_oaep_encrypt<'py>(
        &self,
        py: Python<'py>,
        plaintext: &[u8],
        hash_algorithm: &str,
    ) -> PyResult<Bound<'py, PyBytes>> {
        let ct = self
            .inner
            .rsa_oaep_encrypt(plaintext, hash_algorithm)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(PyBytes::new(py, &ct))
    }

    /// Encrypt ``plaintext`` with RSA PKCS\#1 v1.5 padding.
    ///
    /// Raises :exc:`ValueError` if this key is not an RSA key.
    ///
    /// ```python,ignore
    /// ct = pub.rsa_pkcs1v15_encrypt(b"secret data")
    /// ```
    fn rsa_pkcs1v15_encrypt<'py>(
        &self,
        py: Python<'py>,
        plaintext: &[u8],
    ) -> PyResult<Bound<'py, PyBytes>> {
        let ct = self
            .inner
            .rsa_pkcs1v15_encrypt(plaintext)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(PyBytes::new(py, &ct))
    }

    /// Verify a signature over ``data``.
    ///
    /// ``algorithm`` is the hash algorithm used during signing.  It must be one
    /// of ``"sha1"``, ``"sha224"``, ``"sha256"``, ``"sha384"``, or
    /// ``"sha512"`` for RSA (PKCS\#1 v1.5) and ECDSA keys.  For Ed25519,
    /// Ed448, and ML-DSA keys pass ``None`` (or omit the argument) — no
    /// pre-hash is used.
    ///
    /// ``context`` is the ML-DSA context string (FIPS 204 domain separator).
    /// It defaults to ``b""`` (empty context, equivalent to omitting the
    /// context).  Ignored for non-ML-DSA keys.
    ///
    /// Raises :exc:`ValueError` if the signature is invalid or the algorithm
    /// combination is unsupported.
    ///
    /// ```python,ignore
    /// pub.verify_signature(sig, data, "sha256")              # RSA or ECDSA
    /// ed_pub.verify_signature(sig, data)                     # Ed25519 / Ed448
    /// ml_dsa_pub.verify_signature(sig, data)                 # ML-DSA (empty context)
    /// ml_dsa_pub.verify_signature(sig, data, context=b"app") # ML-DSA with context
    /// ```
    #[pyo3(signature = (signature, data, algorithm = None, context = None))]
    fn verify_signature(
        &self,
        signature: &[u8],
        data: &[u8],
        algorithm: Option<&str>,
        context: Option<&[u8]>,
    ) -> PyResult<()> {
        let kt = self.inner.key_type();
        if matches!(kt, "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87") {
            self.inner
                .verify_ml_dsa_with_context(data, signature, context.unwrap_or(b""))
                .map_err(|e| PyValueError::new_err(format!("{e}")))?;
            return Ok(());
        }
        self.inner
            .verify_message(data, signature, algorithm)
            .map_err(|e| PyValueError::new_err(format!("{e}")))
    }

    /// Verify an X.509 certificate signature given raw DER-encoded components.
    ///
    /// This is the low-level counterpart to :meth:`verify_signature`.  Instead
    /// of an algorithm name string, it accepts a DER-encoded
    /// ``AlgorithmIdentifier`` as found in an X.509 certificate or CRL
    /// ``signatureAlgorithm`` field.  The active crypto backend (NSS when the
    /// ``nss`` feature is compiled in, otherwise OpenSSL) is used for
    /// verification.
    ///
    /// :param tbs_der: DER bytes of the ``TBSCertificate`` (or ``TBSCertList``,
    ///     ``BasicOCSPResponse``, etc.) — the bytes that were signed.
    /// :param sig_alg_der: DER bytes of the ``AlgorithmIdentifier`` SEQUENCE
    ///     from the outer certificate structure.
    /// :param signature: Raw signature bytes (the BIT STRING value, i.e. the
    ///     payload without the tag/length/unused-bits byte).
    /// :raises ValueError: if the signature is invalid or the algorithm is
    ///     unsupported by the active backend.
    ///
    /// ```python,ignore
    /// # Verify the signature on a parsed certificate using its own fields:
    /// pub.verify_certificate_signature(tbs_der, sig_alg_der, sig_bytes)
    /// ```
    fn verify_certificate_signature(
        &self,
        tbs_der: &[u8],
        sig_alg_der: &[u8],
        signature: &[u8],
    ) -> PyResult<()> {
        self.inner
            .verify_signature(tbs_der, sig_alg_der, signature)
            .map_err(|e| PyValueError::new_err(format!("{e}")))
    }

    /// ML-KEM encapsulation: generate a shared secret and a ciphertext.
    ///
    /// Returns a ``(ciphertext, shared_secret)`` tuple.  The holder of the
    /// corresponding private key can call :meth:`PrivateKey.kem_decapsulate`
    /// with ``ciphertext`` to recover ``shared_secret``.
    ///
    /// :raises ValueError: if this key is not an ML-KEM public key.
    ///
    /// ```python,ignore
    /// ct, ss = pub.kem_encapsulate()
    /// ss2    = priv.kem_decapsulate(ct)
    /// assert ss == ss2
    /// ```
    fn kem_encapsulate<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, pyo3::types::PyTuple>> {
        use pyo3::types::PyTuple;
        let (ct, ss) = self
            .inner
            .ml_kem_encapsulate()
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        let items = [PyBytes::new(py, &ct), PyBytes::new(py, &ss)];
        PyTuple::new(py, items)
    }

    fn __repr__(&self) -> String {
        let kt = self.inner.key_type();
        let bits = match kt {
            "ed25519" | "ed448" | "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87" | "ml-kem-512"
            | "ml-kem-768" | "ml-kem-1024" => String::new(),
            _ => self
                .inner
                .key_bit_size()
                .map(|b| format!(", key_size={b}"))
                .unwrap_or_default(),
        };
        format!("PublicKey(key_type={kt:?}{bits})")
    }
}

// ── PrivateKey ────────────────────────────────────────────────────────────────

/// An asymmetric private key.
///
/// Supports RSA, EC (P-256, P-384, P-521), Ed25519, Ed448, and DSA keys.
/// Load from PEM (optionally password-protected) or unencrypted PKCS\#8 DER;
/// serialize back to PEM (optionally encrypted with AES-256-CBC) or
/// unencrypted PKCS\#8 DER.  RSA keys can decrypt ciphertext with OAEP or
/// PKCS\#1 v1.5 padding.
///
/// ```python,ignore
/// import synta
///
/// # Load an encrypted RSA private key from PEM:
/// with open("rsa_key.pem", "rb") as f:
///     priv = synta.PrivateKey.from_pem(f.read(), password=b"secret")
///
/// # Extract the public key:
/// pub = priv.public_key
///
/// # Decrypt RSA-OAEP ciphertext:
/// plaintext = priv.rsa_oaep_decrypt(ciphertext, "sha256")
/// ```
#[pyclass(frozen, name = "PrivateKey")]
pub struct PyPrivateKey {
    pub(crate) inner: BackendPrivateKey,
}

#[pymethods]
impl PyPrivateKey {
    /// Load a private key from PEM-encoded data.
    ///
    /// Supports RSA, EC, Ed25519, Ed448, and DSA keys in both PKCS\#8
    /// (``-----BEGIN PRIVATE KEY-----``) and traditional
    /// (``-----BEGIN RSA PRIVATE KEY-----`` etc.) PEM formats.
    ///
    /// If the PEM block is password-protected, pass the passphrase as
    /// ``password``.
    ///
    /// ```python,ignore
    /// # Unencrypted key:
    /// priv = synta.PrivateKey.from_pem(open("key.pem", "rb").read())
    ///
    /// # Encrypted key:
    /// priv = synta.PrivateKey.from_pem(open("key.pem", "rb").read(), password=b"pass")
    /// ```
    #[staticmethod]
    #[pyo3(signature = (data, password = None))]
    fn from_pem(data: &[u8], password: Option<&[u8]>) -> PyResult<Self> {
        let inner = BackendPrivateKey::from_pem(data, password)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(Self { inner })
    }

    /// Load an unencrypted private key from PKCS\#8 DER bytes.
    ///
    /// ```python,ignore
    /// with open("key.der", "rb") as f:
    ///     priv = synta.PrivateKey.from_der(f.read())
    /// ```
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let inner =
            BackendPrivateKey::from_der(data).map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(Self { inner })
    }

    /// Serialize this private key to PEM-encoded PKCS\#8.
    ///
    /// If ``password`` is provided the output is encrypted with AES-256-CBC.
    ///
    /// ```python,ignore
    /// # Unencrypted:
    /// pem = priv.to_pem()
    ///
    /// # Encrypted:
    /// pem = priv.to_pem(password=b"my-passphrase")
    /// ```
    #[pyo3(signature = (password = None))]
    fn to_pem<'py>(
        &self,
        py: Python<'py>,
        password: Option<&[u8]>,
    ) -> PyResult<Bound<'py, PyBytes>> {
        let pem = self
            .inner
            .to_pem(password)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(PyBytes::new(py, &pem))
    }

    /// Serialize this private key to unencrypted PKCS\#8 DER.
    ///
    /// ```python,ignore
    /// der = priv.to_der()
    /// open("key.der", "wb").write(der)
    /// ```
    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        let der = self
            .inner
            .to_der()
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(PyBytes::new(py, &der))
    }

    /// Serialize this private key to encrypted PKCS\#8 DER
    /// (``EncryptedPrivateKeyInfo``, RFC 5958 §3).
    ///
    /// ```python,ignore
    /// der = priv.to_pkcs8_encrypted(b"my-passphrase")
    /// open("key.p8e", "wb").write(der)
    ///
    /// # Round-trip:
    /// priv2 = synta.PrivateKey.from_pkcs8_encrypted(der, b"my-passphrase")
    /// assert priv2.to_der() == priv.to_der()
    /// ```
    fn to_pkcs8_encrypted<'py>(
        &self,
        py: Python<'py>,
        password: &[u8],
    ) -> PyResult<Bound<'py, PyBytes>> {
        let der = self
            .inner
            .to_pkcs8_encrypted(password)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(PyBytes::new(py, &der))
    }

    /// Load a private key from an encrypted PKCS\#8 DER blob
    /// (``EncryptedPrivateKeyInfo``).
    ///
    /// ```python,ignore
    /// der = open("key.p8e", "rb").read()
    /// priv = synta.PrivateKey.from_pkcs8_encrypted(der, b"my-passphrase")
    /// ```
    #[staticmethod]
    fn from_pkcs8_encrypted(data: &[u8], password: &[u8]) -> PyResult<Self> {
        let inner = BackendPrivateKey::from_pkcs8_encrypted(data, password)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(Self { inner })
    }

    /// Load a private key from a PKCS#11 URI (RFC 7512).
    ///
    /// Requires the OpenSSL PKCS#11 provider or NSS to be configured.
    /// The URI has the form ``pkcs11:token=MyToken;id=%01%02%03;pin-value=1234``.
    ///
    /// Raises :exc:`ValueError` if the URI cannot be parsed or the key cannot be loaded.
    #[staticmethod]
    #[cfg(any(feature = "openssl", feature = "nss"))]
    fn from_pkcs11_uri(uri: &str) -> PyResult<Self> {
        let inner = BackendPrivateKey::from_pkcs11_uri(uri)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(Self { inner })
    }

    /// The key algorithm as a lowercase string.
    ///
    /// Returns one of ``"rsa"``, ``"ec"``, ``"ed25519"``, ``"ed448"``,
    /// ``"dsa"``, or ``"unknown"``.
    #[getter]
    fn key_type(&self) -> &'static str {
        self.inner.key_type()
    }

    /// The key size in bits, or ``None`` for EdDSA keys.
    #[getter]
    fn key_size(&self) -> Option<i64> {
        self.inner.key_bit_size()
    }

    /// The public key corresponding to this private key.
    ///
    /// ```python,ignore
    /// pub = priv.public_key
    /// ct = pub.rsa_oaep_encrypt(b"data", "sha256")
    /// ```
    #[getter]
    fn public_key(&self) -> PyResult<PyPublicKey> {
        let bpk = self
            .inner
            .public_key()
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(PyPublicKey { inner: bpk })
    }

    /// Decrypt ``ciphertext`` with RSA-OAEP using the specified hash algorithm.
    ///
    /// ``hash_algorithm`` must be one of ``"sha1"``, ``"sha224"``,
    /// ``"sha256"``, ``"sha384"``, or ``"sha512"``.
    ///
    /// Raises :exc:`ValueError` if this key is not an RSA key.
    ///
    /// ```python,ignore
    /// plaintext = priv.rsa_oaep_decrypt(ciphertext, "sha256")
    /// ```
    #[pyo3(signature = (ciphertext, hash_algorithm = "sha256"))]
    fn rsa_oaep_decrypt<'py>(
        &self,
        py: Python<'py>,
        ciphertext: &[u8],
        hash_algorithm: &str,
    ) -> PyResult<Bound<'py, PyBytes>> {
        let pt = self
            .inner
            .rsa_oaep_decrypt(ciphertext, hash_algorithm)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(PyBytes::new(py, &pt))
    }

    /// Decrypt ``ciphertext`` with RSA PKCS\#1 v1.5 padding.
    ///
    /// Raises :exc:`ValueError` if this key is not an RSA key.
    ///
    /// ```python,ignore
    /// plaintext = priv.rsa_pkcs1v15_decrypt(ciphertext)
    /// ```
    fn rsa_pkcs1v15_decrypt<'py>(
        &self,
        py: Python<'py>,
        ciphertext: &[u8],
    ) -> PyResult<Bound<'py, PyBytes>> {
        let pt = self
            .inner
            .rsa_pkcs1v15_decrypt(ciphertext)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(PyBytes::new(py, &pt))
    }

    /// Generate a new RSA private key.
    ///
    /// ``key_size`` is the modulus bit-length (e.g. 2048, 3072, 4096).
    /// ``public_exponent`` defaults to 65537.
    ///
    /// ```python,ignore
    /// priv = synta.PrivateKey.generate_rsa(2048)
    /// ```
    #[staticmethod]
    #[pyo3(signature = (key_size, public_exponent = 65537))]
    fn generate_rsa(key_size: u32, public_exponent: u32) -> PyResult<Self> {
        let inner = BackendPrivateKey::generate_rsa(key_size, public_exponent)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(Self { inner })
    }

    /// Generate a new EC private key on the specified named curve.
    ///
    /// ``curve`` must be one of ``"P-256"``, ``"P-384"``, or ``"P-521"``.
    /// Raises :exc:`ValueError` for unknown curve names.
    ///
    /// ```python,ignore
    /// priv = synta.PrivateKey.generate_ec("P-256")
    /// ```
    #[staticmethod]
    #[pyo3(signature = (curve = "P-256"))]
    fn generate_ec(curve: &str) -> PyResult<Self> {
        let inner = BackendPrivateKey::generate_ec(curve)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(Self { inner })
    }

    /// Generate a new Ed25519 private key (RFC 8032).
    ///
    /// ```python,ignore
    /// priv = synta.PrivateKey.generate_ed25519()
    /// pub  = priv.public_key
    /// ```
    #[staticmethod]
    fn generate_ed25519() -> PyResult<Self> {
        let inner = BackendPrivateKey::generate_ed25519()
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(Self { inner })
    }

    /// Generate a new Ed448 private key (RFC 8032).
    ///
    /// ```python,ignore
    /// priv = synta.PrivateKey.generate_ed448()
    /// pub  = priv.public_key
    /// ```
    #[staticmethod]
    fn generate_ed448() -> PyResult<Self> {
        let inner = BackendPrivateKey::generate_ed448()
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(Self { inner })
    }

    /// Generate a new ML-DSA private key (FIPS 204).
    ///
    /// ``parameter_set`` must be one of ``"ML-DSA-44"``, ``"ML-DSA-65"``, or
    /// ``"ML-DSA-87"``.  Requires OpenSSL 3.5 or newer.
    ///
    /// ```python,ignore
    /// priv = synta.PrivateKey.generate_ml_dsa("ML-DSA-65")
    /// pub  = priv.public_key
    /// sig  = priv.sign(message)
    /// ```
    #[staticmethod]
    fn generate_ml_dsa(parameter_set: &str) -> PyResult<Self> {
        let inner = BackendPrivateKey::generate_ml_dsa(parameter_set)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(Self { inner })
    }

    /// Generate a new composite ML-DSA private key (draft-ietf-lamps-pq-composite-sigs-19).
    ///
    /// ``sub_arc`` selects the composite variant by its OID sub-arc (37–54):
    ///
    /// | sub_arc | Algorithm |
    /// |---------|-----------|
    /// | 37 | MLDSA44-RSA2048-PSS-SHA256 |
    /// | 38 | MLDSA44-RSA2048-PKCS15-SHA256 |
    /// | 39 | MLDSA44-Ed25519-SHA512 |
    /// | 40 | MLDSA44-ECDSA-P256-SHA256 |
    /// | 41 | MLDSA65-RSA3072-PSS-SHA512 |
    /// | 42 | MLDSA65-RSA3072-PKCS15-SHA512 |
    /// | 43 | MLDSA65-RSA4096-PSS-SHA512 |
    /// | 44 | MLDSA65-RSA4096-PKCS15-SHA512 |
    /// | 45 | MLDSA65-ECDSA-P256-SHA512 |
    /// | 46 | MLDSA65-ECDSA-P384-SHA512 |
    /// | 47 | MLDSA65-ECDSA-brainpoolP256r1-SHA512 |
    /// | 48 | MLDSA65-Ed25519-SHA512 |
    /// | 49 | MLDSA87-ECDSA-P384-SHA512 |
    /// | 50 | MLDSA87-ECDSA-brainpoolP384r1-SHA512 |
    /// | 51 | MLDSA87-Ed448-SHAKE256 |
    /// | 52 | MLDSA87-RSA3072-PSS-SHA512 |
    /// | 53 | MLDSA87-RSA4096-PSS-SHA512 |
    /// | 54 | MLDSA87-ECDSA-P521-SHA512 |
    ///
    /// Requires OpenSSL 3.3+ (with ML-DSA support) and the ``pqc`` Cargo
    /// feature, or NSS.
    ///
    /// ```python,ignore
    /// # Generate MLDSA65-ECDSA-P256-SHA512 (sub_arc=45)
    /// priv = synta.PrivateKey.generate_composite_ml_dsa(45)
    /// ```
    #[staticmethod]
    fn generate_composite_ml_dsa(sub_arc: u32) -> PyResult<Self> {
        let inner = synta_certificate::BackendPrivateKey::generate_composite_ml_dsa(sub_arc)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(Self { inner })
    }

    /// Generate a new ML-KEM private key (FIPS 203).
    ///
    /// ``parameter_set`` must be one of ``"ML-KEM-512"``, ``"ML-KEM-768"``, or
    /// ``"ML-KEM-1024"``.  Requires OpenSSL 3.5 or newer.
    ///
    /// ```python,ignore
    /// priv = synta.PrivateKey.generate_ml_kem("ML-KEM-768")
    /// pub  = priv.public_key
    /// ct, ss = pub.kem_encapsulate()
    /// ss2    = priv.kem_decapsulate(ct)
    /// assert ss == ss2
    /// ```
    #[staticmethod]
    fn generate_ml_kem(parameter_set: &str) -> PyResult<Self> {
        let inner = BackendPrivateKey::generate_ml_kem(parameter_set)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(Self { inner })
    }

    /// ML-KEM decapsulation: recover the shared secret from ``ciphertext``.
    ///
    /// The ``ciphertext`` must have been produced by the peer calling
    /// :meth:`PublicKey.kem_encapsulate` on the corresponding public key.
    ///
    /// :raises ValueError: if this key is not an ML-KEM key or decapsulation fails.
    ///
    /// ```python,ignore
    /// shared_secret = priv.kem_decapsulate(ciphertext)
    /// ```
    fn kem_decapsulate<'py>(
        &self,
        py: Python<'py>,
        ciphertext: &[u8],
    ) -> PyResult<Bound<'py, PyBytes>> {
        let ss = self
            .inner
            .ml_kem_decapsulate(ciphertext)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(PyBytes::new(py, &ss))
    }

    /// Sign ``data`` with this private key and return the raw signature bytes.
    ///
    /// ``algorithm`` is the hash algorithm used during signing (e.g.
    /// ``"sha256"`` for RSA PKCS\#1 v1.5 and ECDSA).  For Ed25519, Ed448,
    /// and ML-DSA keys pass ``None`` (or omit the argument) — no pre-hash is
    /// used.
    ///
    /// ``context`` is the ML-DSA context string (FIPS 204 domain separator).
    /// It defaults to ``b""`` (empty context, equivalent to omitting the
    /// context).  Ignored for non-ML-DSA keys.
    ///
    /// This method signs arbitrary bytes; it is the caller's responsibility to
    /// hash the data if required by the algorithm (Ed25519 / Ed448 / ML-DSA
    /// hash internally and must receive the original message, not a pre-hash).
    ///
    /// :raises ValueError: if the algorithm is unknown or signing fails.
    ///
    /// ```python,ignore
    /// priv = synta.PrivateKey.generate_ec("P-256")
    /// sig  = priv.sign(tbs_der, "sha256")
    /// priv.public_key.verify_signature(sig, tbs_der, "sha256")
    ///
    /// ml_priv = synta.PrivateKey.generate_ml_dsa("ML-DSA-65")
    /// sig = ml_priv.sign(message, context=b"my-app")
    /// ml_priv.public_key.verify_signature(sig, message, context=b"my-app")
    /// ```
    #[pyo3(signature = (data, algorithm = None, context = None))]
    fn sign<'py>(
        &self,
        py: Python<'py>,
        data: &[u8],
        algorithm: Option<&str>,
        context: Option<&[u8]>,
    ) -> PyResult<Bound<'py, PyBytes>> {
        let kt = self.inner.key_type();
        if matches!(kt, "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87") {
            let sig = self
                .inner
                .sign_ml_dsa_with_context(data, context.unwrap_or(b""))
                .map_err(|e| PyValueError::new_err(format!("{e}")))?;
            return Ok(PyBytes::new(py, &sig));
        }
        let alg = algorithm.unwrap_or("sha256");
        let signer = self.inner.as_signer(alg);
        let sig = signer
            .sign_tbs_erased(data)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        Ok(PyBytes::new(py, &sig))
    }

    fn __repr__(&self) -> String {
        let kt = self.inner.key_type();
        let bits = match kt {
            "ed25519" | "ed448" | "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87" | "ml-kem-512"
            | "ml-kem-768" | "ml-kem-1024" => String::new(),
            _ => self
                .inner
                .key_bit_size()
                .map(|b| format!(", key_size={b}"))
                .unwrap_or_default(),
        };
        format!("PrivateKey(key_type={kt:?}{bits})")
    }
}

// ── PrivateKey trait impl ─────────────────────────────────────────────────────

/// Implement the backend-agnostic [`synta_certificate::PrivateKey`] trait for
/// [`PyPrivateKey`] by delegating to [`synta_certificate::BackendPrivateKey`].
///
/// This allows Python binding code (e.g. `cert_builder.rs`) to call
/// `key.as_signer(algorithm)` without importing backend-specific types.
impl synta_certificate::PrivateKey for PyPrivateKey {
    fn public_key_spki_der(&self) -> Result<Vec<u8>, synta_certificate::PrivateKeyError> {
        self.inner.public_key_spki_der()
    }

    fn as_signer(&self, algorithm: &str) -> Box<dyn synta_certificate::ErasedCertificateSigner> {
        self.inner.as_signer(algorithm)
    }
}