Skip to main content

_synta/
crypto_keys.rs

1//! Python bindings for generic public and private key operations.
2//!
3//! Exposes [`PyPublicKey`] and [`PyPrivateKey`] as pyo3 classes supporting
4//! RSA, EC, EdDSA, and DSA keys via the `synta-certificate` backend traits.
5//! No direct `openssl::*` imports are used here.
6
7use pyo3::exceptions::PyValueError;
8use pyo3::prelude::*;
9use pyo3::types::PyBytes;
10use synta_certificate::{BackendPrivateKey, BackendPublicKey, PrivateKey};
11
12// ── PublicKey ─────────────────────────────────────────────────────────────────
13
14/// An asymmetric public key.
15///
16/// Supports RSA, EC (P-256, P-384, P-521), Ed25519, Ed448, and DSA keys.
17/// Load from PEM or SubjectPublicKeyInfo DER; serialize back to PEM or DER.
18/// RSA keys can encrypt data with OAEP or PKCS\#1 v1.5 padding.
19///
20/// ```python,ignore
21/// import synta
22///
23/// # Load an RSA public key from a PEM file:
24/// with open("rsa_pub.pem", "rb") as f:
25///     pub = synta.PublicKey.from_pem(f.read())
26/// print(pub.key_type)   # "rsa"
27/// print(pub.key_size)   # e.g. 2048
28///
29/// # Encrypt with OAEP (SHA-256):
30/// ct = pub.rsa_oaep_encrypt(b"secret", "sha256")
31///
32/// # Load an EC public key from SPKI DER:
33/// ec_pub = synta.PublicKey.from_der(spki_der)
34/// print(ec_pub.curve_name)  # "P-256"
35/// ```
36#[pyclass(frozen, name = "PublicKey")]
37pub struct PyPublicKey {
38    pub(crate) inner: BackendPublicKey,
39}
40
41#[pymethods]
42impl PyPublicKey {
43    /// Load a public key from PEM-encoded SubjectPublicKeyInfo data.
44    ///
45    /// Supports RSA, EC (P-256, P-384, P-521), Ed25519, Ed448, and DSA keys.
46    ///
47    /// ```python,ignore
48    /// with open("pubkey.pem", "rb") as f:
49    ///     pub = synta.PublicKey.from_pem(f.read())
50    /// ```
51    #[staticmethod]
52    fn from_pem(data: &[u8]) -> PyResult<Self> {
53        let inner =
54            BackendPublicKey::from_pem(data).map_err(|e| PyValueError::new_err(format!("{e}")))?;
55        Ok(Self { inner })
56    }
57
58    /// Construct an RSA public key from raw big-endian modulus *n* and public-exponent *e* bytes.
59    ///
60    /// This is the inverse of the :attr:`modulus` and :attr:`public_exponent` getters.
61    /// Raises :exc:`ValueError` if the inputs do not encode a valid RSA key.
62    ///
63    /// ```python,ignore
64    /// # n and e are big-endian bytes (e.g. extracted from a PKCS#11 token)
65    /// pub = synta.PublicKey.from_rsa_components(n, e)
66    /// assert pub.key_type == "rsa"
67    /// ```
68    #[staticmethod]
69    fn from_rsa_components(n: &[u8], e: &[u8]) -> PyResult<Self> {
70        let inner = BackendPublicKey::from_rsa_components(n, e)
71            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
72        Ok(Self { inner })
73    }
74
75    /// Construct an EC public key from affine coordinates *x* and *y* (big-endian
76    /// bytes) and a NIST curve name (``"P-256"``, ``"P-384"``, or ``"P-521"``).
77    ///
78    /// This is the inverse of the :attr:`x`, :attr:`y`, and :attr:`curve_name` getters.
79    /// Raises :exc:`ValueError` for unknown curve names or invalid coordinates.
80    ///
81    /// ```python,ignore
82    /// pub = synta.PublicKey.from_ec_components(x_bytes, y_bytes, "P-256")
83    /// assert pub.key_type == "ec"
84    /// ```
85    #[staticmethod]
86    fn from_ec_components(x: &[u8], y: &[u8], curve: &str) -> PyResult<Self> {
87        let inner = BackendPublicKey::from_ec_components(x, y, curve)
88            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
89        Ok(Self { inner })
90    }
91
92    /// Load a public key from a DER-encoded SubjectPublicKeyInfo structure.
93    ///
94    /// ```python,ignore
95    /// with open("pubkey.der", "rb") as f:
96    ///     pub = synta.PublicKey.from_der(f.read())
97    /// ```
98    #[staticmethod]
99    fn from_der(data: &[u8]) -> PyResult<Self> {
100        let inner =
101            BackendPublicKey::from_der(data).map_err(|e| PyValueError::new_err(format!("{e}")))?;
102        Ok(Self { inner })
103    }
104
105    /// Serialize this public key to PEM-encoded SubjectPublicKeyInfo.
106    ///
107    /// ```python,ignore
108    /// pem = pub.to_pem()
109    /// open("pubkey.pem", "wb").write(pem)
110    /// ```
111    fn to_pem<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
112        let pem = self
113            .inner
114            .to_pem()
115            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
116        Ok(PyBytes::new(py, &pem))
117    }
118
119    /// Serialize this public key to DER-encoded SubjectPublicKeyInfo.
120    ///
121    /// ```python,ignore
122    /// der = pub.to_der()
123    /// open("pubkey.der", "wb").write(der)
124    /// ```
125    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
126        let der = self
127            .inner
128            .to_der()
129            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
130        Ok(PyBytes::new(py, &der))
131    }
132
133    /// The key algorithm as a lowercase string.
134    ///
135    /// Returns one of ``"rsa"``, ``"ec"``, ``"ed25519"``, ``"ed448"``,
136    /// ``"dsa"``, or ``"unknown"``.
137    #[getter]
138    fn key_type(&self) -> &'static str {
139        self.inner.key_type()
140    }
141
142    /// The key size in bits, or ``None`` for EdDSA keys.
143    ///
144    /// For RSA this is the modulus bit-length; for EC this is the field
145    /// bit-length.  Returns ``None`` for Ed25519 and Ed448.
146    #[getter]
147    fn key_size(&self) -> Option<i64> {
148        self.inner.key_bit_size()
149    }
150
151    /// The RSA modulus ``n`` as big-endian bytes, or ``None`` for non-RSA keys.
152    #[getter]
153    fn modulus<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyBytes>>> {
154        match self
155            .inner
156            .rsa_modulus()
157            .map_err(|e| PyValueError::new_err(format!("{e}")))?
158        {
159            Some(n) => Ok(Some(PyBytes::new(py, &n))),
160            None => Ok(None),
161        }
162    }
163
164    /// The RSA public exponent ``e`` as big-endian bytes, or ``None`` for
165    /// non-RSA keys.
166    ///
167    /// The most common value is ``b'\x01\x00\x01'`` (65537).
168    #[getter]
169    fn public_exponent<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyBytes>>> {
170        match self
171            .inner
172            .rsa_public_exponent()
173            .map_err(|e| PyValueError::new_err(format!("{e}")))?
174        {
175            Some(e) => Ok(Some(PyBytes::new(py, &e))),
176            None => Ok(None),
177        }
178    }
179
180    /// The NIST curve name for EC keys, or ``None`` for non-EC keys.
181    ///
182    /// Returns ``"P-256"``, ``"P-384"``, ``"P-521"``, or ``"unknown"`` for
183    /// EC keys on other curves.
184    #[getter]
185    fn curve_name(&self) -> PyResult<Option<&'static str>> {
186        self.inner
187            .ec_curve_name()
188            .map_err(|e| PyValueError::new_err(format!("{e}")))
189    }
190
191    /// The affine X coordinate of the EC public key as big-endian bytes, or
192    /// ``None`` for non-EC keys.
193    #[getter]
194    fn x<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyBytes>>> {
195        match self
196            .inner
197            .ec_affine_coordinates()
198            .map_err(|e| PyValueError::new_err(format!("{e}")))?
199        {
200            Some((xv, _)) => Ok(Some(PyBytes::new(py, &xv))),
201            None => Ok(None),
202        }
203    }
204
205    /// The affine Y coordinate of the EC public key as big-endian bytes, or
206    /// ``None`` for non-EC keys.
207    #[getter]
208    fn y<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyBytes>>> {
209        match self
210            .inner
211            .ec_affine_coordinates()
212            .map_err(|e| PyValueError::new_err(format!("{e}")))?
213        {
214            Some((_, yv)) => Ok(Some(PyBytes::new(py, &yv))),
215            None => Ok(None),
216        }
217    }
218
219    /// Encrypt ``plaintext`` with RSA-OAEP using the specified hash algorithm.
220    ///
221    /// ``hash_algorithm`` must be one of ``"sha1"``, ``"sha224"``,
222    /// ``"sha256"``, ``"sha384"``, or ``"sha512"``.
223    ///
224    /// Raises :exc:`ValueError` if this key is not an RSA key.
225    ///
226    /// ```python,ignore
227    /// ct = pub.rsa_oaep_encrypt(b"secret data", "sha256")
228    /// ```
229    #[pyo3(signature = (plaintext, hash_algorithm = "sha256"))]
230    fn rsa_oaep_encrypt<'py>(
231        &self,
232        py: Python<'py>,
233        plaintext: &[u8],
234        hash_algorithm: &str,
235    ) -> PyResult<Bound<'py, PyBytes>> {
236        let ct = self
237            .inner
238            .rsa_oaep_encrypt(plaintext, hash_algorithm)
239            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
240        Ok(PyBytes::new(py, &ct))
241    }
242
243    /// Encrypt ``plaintext`` with RSA PKCS\#1 v1.5 padding.
244    ///
245    /// Raises :exc:`ValueError` if this key is not an RSA key.
246    ///
247    /// ```python,ignore
248    /// ct = pub.rsa_pkcs1v15_encrypt(b"secret data")
249    /// ```
250    fn rsa_pkcs1v15_encrypt<'py>(
251        &self,
252        py: Python<'py>,
253        plaintext: &[u8],
254    ) -> PyResult<Bound<'py, PyBytes>> {
255        let ct = self
256            .inner
257            .rsa_pkcs1v15_encrypt(plaintext)
258            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
259        Ok(PyBytes::new(py, &ct))
260    }
261
262    /// Verify a signature over ``data``.
263    ///
264    /// ``algorithm`` is the hash algorithm used during signing.  It must be one
265    /// of ``"sha1"``, ``"sha224"``, ``"sha256"``, ``"sha384"``, or
266    /// ``"sha512"`` for RSA (PKCS\#1 v1.5) and ECDSA keys.  For Ed25519,
267    /// Ed448, and ML-DSA keys pass ``None`` (or omit the argument) — no
268    /// pre-hash is used.
269    ///
270    /// ``context`` is the ML-DSA context string (FIPS 204 domain separator).
271    /// It defaults to ``b""`` (empty context, equivalent to omitting the
272    /// context).  Ignored for non-ML-DSA keys.
273    ///
274    /// Raises :exc:`ValueError` if the signature is invalid or the algorithm
275    /// combination is unsupported.
276    ///
277    /// ```python,ignore
278    /// pub.verify_signature(sig, data, "sha256")              # RSA or ECDSA
279    /// ed_pub.verify_signature(sig, data)                     # Ed25519 / Ed448
280    /// ml_dsa_pub.verify_signature(sig, data)                 # ML-DSA (empty context)
281    /// ml_dsa_pub.verify_signature(sig, data, context=b"app") # ML-DSA with context
282    /// ```
283    #[pyo3(signature = (signature, data, algorithm = None, context = None))]
284    fn verify_signature(
285        &self,
286        signature: &[u8],
287        data: &[u8],
288        algorithm: Option<&str>,
289        context: Option<&[u8]>,
290    ) -> PyResult<()> {
291        let kt = self.inner.key_type();
292        if matches!(kt, "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87") {
293            self.inner
294                .verify_ml_dsa_with_context(data, signature, context.unwrap_or(b""))
295                .map_err(|e| PyValueError::new_err(format!("{e}")))?;
296            return Ok(());
297        }
298        self.inner
299            .verify_message(data, signature, algorithm)
300            .map_err(|e| PyValueError::new_err(format!("{e}")))
301    }
302
303    /// Verify an X.509 certificate signature given raw DER-encoded components.
304    ///
305    /// This is the low-level counterpart to :meth:`verify_signature`.  Instead
306    /// of an algorithm name string, it accepts a DER-encoded
307    /// ``AlgorithmIdentifier`` as found in an X.509 certificate or CRL
308    /// ``signatureAlgorithm`` field.  The active crypto backend (NSS when the
309    /// ``nss`` feature is compiled in, otherwise OpenSSL) is used for
310    /// verification.
311    ///
312    /// :param tbs_der: DER bytes of the ``TBSCertificate`` (or ``TBSCertList``,
313    ///     ``BasicOCSPResponse``, etc.) — the bytes that were signed.
314    /// :param sig_alg_der: DER bytes of the ``AlgorithmIdentifier`` SEQUENCE
315    ///     from the outer certificate structure.
316    /// :param signature: Raw signature bytes (the BIT STRING value, i.e. the
317    ///     payload without the tag/length/unused-bits byte).
318    /// :raises ValueError: if the signature is invalid or the algorithm is
319    ///     unsupported by the active backend.
320    ///
321    /// ```python,ignore
322    /// # Verify the signature on a parsed certificate using its own fields:
323    /// pub.verify_certificate_signature(tbs_der, sig_alg_der, sig_bytes)
324    /// ```
325    fn verify_certificate_signature(
326        &self,
327        tbs_der: &[u8],
328        sig_alg_der: &[u8],
329        signature: &[u8],
330    ) -> PyResult<()> {
331        self.inner
332            .verify_signature(tbs_der, sig_alg_der, signature)
333            .map_err(|e| PyValueError::new_err(format!("{e}")))
334    }
335
336    /// ML-KEM encapsulation: generate a shared secret and a ciphertext.
337    ///
338    /// Returns a ``(ciphertext, shared_secret)`` tuple.  The holder of the
339    /// corresponding private key can call :meth:`PrivateKey.kem_decapsulate`
340    /// with ``ciphertext`` to recover ``shared_secret``.
341    ///
342    /// :raises ValueError: if this key is not an ML-KEM public key.
343    ///
344    /// ```python,ignore
345    /// ct, ss = pub.kem_encapsulate()
346    /// ss2    = priv.kem_decapsulate(ct)
347    /// assert ss == ss2
348    /// ```
349    fn kem_encapsulate<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, pyo3::types::PyTuple>> {
350        use pyo3::types::PyTuple;
351        let (ct, ss) = self
352            .inner
353            .ml_kem_encapsulate()
354            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
355        let items = [PyBytes::new(py, &ct), PyBytes::new(py, &ss)];
356        PyTuple::new(py, items)
357    }
358
359    fn __repr__(&self) -> String {
360        let kt = self.inner.key_type();
361        let bits = match kt {
362            "ed25519" | "ed448" | "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87" | "ml-kem-512"
363            | "ml-kem-768" | "ml-kem-1024" => String::new(),
364            _ => self
365                .inner
366                .key_bit_size()
367                .map(|b| format!(", key_size={b}"))
368                .unwrap_or_default(),
369        };
370        format!("PublicKey(key_type={kt:?}{bits})")
371    }
372}
373
374// ── PrivateKey ────────────────────────────────────────────────────────────────
375
376/// An asymmetric private key.
377///
378/// Supports RSA, EC (P-256, P-384, P-521), Ed25519, Ed448, and DSA keys.
379/// Load from PEM (optionally password-protected) or unencrypted PKCS\#8 DER;
380/// serialize back to PEM (optionally encrypted with AES-256-CBC) or
381/// unencrypted PKCS\#8 DER.  RSA keys can decrypt ciphertext with OAEP or
382/// PKCS\#1 v1.5 padding.
383///
384/// ```python,ignore
385/// import synta
386///
387/// # Load an encrypted RSA private key from PEM:
388/// with open("rsa_key.pem", "rb") as f:
389///     priv = synta.PrivateKey.from_pem(f.read(), password=b"secret")
390///
391/// # Extract the public key:
392/// pub = priv.public_key
393///
394/// # Decrypt RSA-OAEP ciphertext:
395/// plaintext = priv.rsa_oaep_decrypt(ciphertext, "sha256")
396/// ```
397#[pyclass(frozen, name = "PrivateKey")]
398pub struct PyPrivateKey {
399    pub(crate) inner: BackendPrivateKey,
400}
401
402#[pymethods]
403impl PyPrivateKey {
404    /// Load a private key from PEM-encoded data.
405    ///
406    /// Supports RSA, EC, Ed25519, Ed448, and DSA keys in both PKCS\#8
407    /// (``-----BEGIN PRIVATE KEY-----``) and traditional
408    /// (``-----BEGIN RSA PRIVATE KEY-----`` etc.) PEM formats.
409    ///
410    /// If the PEM block is password-protected, pass the passphrase as
411    /// ``password``.
412    ///
413    /// ```python,ignore
414    /// # Unencrypted key:
415    /// priv = synta.PrivateKey.from_pem(open("key.pem", "rb").read())
416    ///
417    /// # Encrypted key:
418    /// priv = synta.PrivateKey.from_pem(open("key.pem", "rb").read(), password=b"pass")
419    /// ```
420    #[staticmethod]
421    #[pyo3(signature = (data, password = None))]
422    fn from_pem(data: &[u8], password: Option<&[u8]>) -> PyResult<Self> {
423        let inner = BackendPrivateKey::from_pem(data, password)
424            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
425        Ok(Self { inner })
426    }
427
428    /// Load an unencrypted private key from PKCS\#8 DER bytes.
429    ///
430    /// ```python,ignore
431    /// with open("key.der", "rb") as f:
432    ///     priv = synta.PrivateKey.from_der(f.read())
433    /// ```
434    #[staticmethod]
435    fn from_der(data: &[u8]) -> PyResult<Self> {
436        let inner =
437            BackendPrivateKey::from_der(data).map_err(|e| PyValueError::new_err(format!("{e}")))?;
438        Ok(Self { inner })
439    }
440
441    /// Serialize this private key to PEM-encoded PKCS\#8.
442    ///
443    /// If ``password`` is provided the output is encrypted with AES-256-CBC.
444    ///
445    /// ```python,ignore
446    /// # Unencrypted:
447    /// pem = priv.to_pem()
448    ///
449    /// # Encrypted:
450    /// pem = priv.to_pem(password=b"my-passphrase")
451    /// ```
452    #[pyo3(signature = (password = None))]
453    fn to_pem<'py>(
454        &self,
455        py: Python<'py>,
456        password: Option<&[u8]>,
457    ) -> PyResult<Bound<'py, PyBytes>> {
458        let pem = self
459            .inner
460            .to_pem(password)
461            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
462        Ok(PyBytes::new(py, &pem))
463    }
464
465    /// Serialize this private key to unencrypted PKCS\#8 DER.
466    ///
467    /// ```python,ignore
468    /// der = priv.to_der()
469    /// open("key.der", "wb").write(der)
470    /// ```
471    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
472        let der = self
473            .inner
474            .to_der()
475            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
476        Ok(PyBytes::new(py, &der))
477    }
478
479    /// Serialize this private key to encrypted PKCS\#8 DER
480    /// (``EncryptedPrivateKeyInfo``, RFC 5958 §3).
481    ///
482    /// ```python,ignore
483    /// der = priv.to_pkcs8_encrypted(b"my-passphrase")
484    /// open("key.p8e", "wb").write(der)
485    ///
486    /// # Round-trip:
487    /// priv2 = synta.PrivateKey.from_pkcs8_encrypted(der, b"my-passphrase")
488    /// assert priv2.to_der() == priv.to_der()
489    /// ```
490    fn to_pkcs8_encrypted<'py>(
491        &self,
492        py: Python<'py>,
493        password: &[u8],
494    ) -> PyResult<Bound<'py, PyBytes>> {
495        let der = self
496            .inner
497            .to_pkcs8_encrypted(password)
498            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
499        Ok(PyBytes::new(py, &der))
500    }
501
502    /// Load a private key from an encrypted PKCS\#8 DER blob
503    /// (``EncryptedPrivateKeyInfo``).
504    ///
505    /// ```python,ignore
506    /// der = open("key.p8e", "rb").read()
507    /// priv = synta.PrivateKey.from_pkcs8_encrypted(der, b"my-passphrase")
508    /// ```
509    #[staticmethod]
510    fn from_pkcs8_encrypted(data: &[u8], password: &[u8]) -> PyResult<Self> {
511        let inner = BackendPrivateKey::from_pkcs8_encrypted(data, password)
512            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
513        Ok(Self { inner })
514    }
515
516    /// The key algorithm as a lowercase string.
517    ///
518    /// Returns one of ``"rsa"``, ``"ec"``, ``"ed25519"``, ``"ed448"``,
519    /// ``"dsa"``, or ``"unknown"``.
520    #[getter]
521    fn key_type(&self) -> &'static str {
522        self.inner.key_type()
523    }
524
525    /// The key size in bits, or ``None`` for EdDSA keys.
526    #[getter]
527    fn key_size(&self) -> Option<i64> {
528        self.inner.key_bit_size()
529    }
530
531    /// The public key corresponding to this private key.
532    ///
533    /// ```python,ignore
534    /// pub = priv.public_key
535    /// ct = pub.rsa_oaep_encrypt(b"data", "sha256")
536    /// ```
537    #[getter]
538    fn public_key(&self) -> PyResult<PyPublicKey> {
539        let bpk = self
540            .inner
541            .public_key()
542            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
543        Ok(PyPublicKey { inner: bpk })
544    }
545
546    /// Decrypt ``ciphertext`` with RSA-OAEP using the specified hash algorithm.
547    ///
548    /// ``hash_algorithm`` must be one of ``"sha1"``, ``"sha224"``,
549    /// ``"sha256"``, ``"sha384"``, or ``"sha512"``.
550    ///
551    /// Raises :exc:`ValueError` if this key is not an RSA key.
552    ///
553    /// ```python,ignore
554    /// plaintext = priv.rsa_oaep_decrypt(ciphertext, "sha256")
555    /// ```
556    #[pyo3(signature = (ciphertext, hash_algorithm = "sha256"))]
557    fn rsa_oaep_decrypt<'py>(
558        &self,
559        py: Python<'py>,
560        ciphertext: &[u8],
561        hash_algorithm: &str,
562    ) -> PyResult<Bound<'py, PyBytes>> {
563        let pt = self
564            .inner
565            .rsa_oaep_decrypt(ciphertext, hash_algorithm)
566            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
567        Ok(PyBytes::new(py, &pt))
568    }
569
570    /// Decrypt ``ciphertext`` with RSA PKCS\#1 v1.5 padding.
571    ///
572    /// Raises :exc:`ValueError` if this key is not an RSA key.
573    ///
574    /// ```python,ignore
575    /// plaintext = priv.rsa_pkcs1v15_decrypt(ciphertext)
576    /// ```
577    fn rsa_pkcs1v15_decrypt<'py>(
578        &self,
579        py: Python<'py>,
580        ciphertext: &[u8],
581    ) -> PyResult<Bound<'py, PyBytes>> {
582        let pt = self
583            .inner
584            .rsa_pkcs1v15_decrypt(ciphertext)
585            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
586        Ok(PyBytes::new(py, &pt))
587    }
588
589    /// Generate a new RSA private key.
590    ///
591    /// ``key_size`` is the modulus bit-length (e.g. 2048, 3072, 4096).
592    /// ``public_exponent`` defaults to 65537.
593    ///
594    /// ```python,ignore
595    /// priv = synta.PrivateKey.generate_rsa(2048)
596    /// ```
597    #[staticmethod]
598    #[pyo3(signature = (key_size, public_exponent = 65537))]
599    fn generate_rsa(key_size: u32, public_exponent: u32) -> PyResult<Self> {
600        let inner = BackendPrivateKey::generate_rsa(key_size, public_exponent)
601            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
602        Ok(Self { inner })
603    }
604
605    /// Generate a new EC private key on the specified named curve.
606    ///
607    /// ``curve`` must be one of ``"P-256"``, ``"P-384"``, or ``"P-521"``.
608    /// Raises :exc:`ValueError` for unknown curve names.
609    ///
610    /// ```python,ignore
611    /// priv = synta.PrivateKey.generate_ec("P-256")
612    /// ```
613    #[staticmethod]
614    #[pyo3(signature = (curve = "P-256"))]
615    fn generate_ec(curve: &str) -> PyResult<Self> {
616        let inner = BackendPrivateKey::generate_ec(curve)
617            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
618        Ok(Self { inner })
619    }
620
621    /// Generate a new Ed25519 private key (RFC 8032).
622    ///
623    /// ```python,ignore
624    /// priv = synta.PrivateKey.generate_ed25519()
625    /// pub  = priv.public_key
626    /// ```
627    #[staticmethod]
628    fn generate_ed25519() -> PyResult<Self> {
629        let inner = BackendPrivateKey::generate_ed25519()
630            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
631        Ok(Self { inner })
632    }
633
634    /// Generate a new Ed448 private key (RFC 8032).
635    ///
636    /// ```python,ignore
637    /// priv = synta.PrivateKey.generate_ed448()
638    /// pub  = priv.public_key
639    /// ```
640    #[staticmethod]
641    fn generate_ed448() -> PyResult<Self> {
642        let inner = BackendPrivateKey::generate_ed448()
643            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
644        Ok(Self { inner })
645    }
646
647    /// Generate a new ML-DSA private key (FIPS 204).
648    ///
649    /// ``parameter_set`` must be one of ``"ML-DSA-44"``, ``"ML-DSA-65"``, or
650    /// ``"ML-DSA-87"``.  Requires OpenSSL 3.5 or newer.
651    ///
652    /// ```python,ignore
653    /// priv = synta.PrivateKey.generate_ml_dsa("ML-DSA-65")
654    /// pub  = priv.public_key
655    /// sig  = priv.sign(message)
656    /// ```
657    #[staticmethod]
658    fn generate_ml_dsa(parameter_set: &str) -> PyResult<Self> {
659        let inner = BackendPrivateKey::generate_ml_dsa(parameter_set)
660            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
661        Ok(Self { inner })
662    }
663
664    /// Generate a new ML-KEM private key (FIPS 203).
665    ///
666    /// ``parameter_set`` must be one of ``"ML-KEM-512"``, ``"ML-KEM-768"``, or
667    /// ``"ML-KEM-1024"``.  Requires OpenSSL 3.5 or newer.
668    ///
669    /// ```python,ignore
670    /// priv = synta.PrivateKey.generate_ml_kem("ML-KEM-768")
671    /// pub  = priv.public_key
672    /// ct, ss = pub.kem_encapsulate()
673    /// ss2    = priv.kem_decapsulate(ct)
674    /// assert ss == ss2
675    /// ```
676    #[staticmethod]
677    fn generate_ml_kem(parameter_set: &str) -> PyResult<Self> {
678        let inner = BackendPrivateKey::generate_ml_kem(parameter_set)
679            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
680        Ok(Self { inner })
681    }
682
683    /// ML-KEM decapsulation: recover the shared secret from ``ciphertext``.
684    ///
685    /// The ``ciphertext`` must have been produced by the peer calling
686    /// :meth:`PublicKey.kem_encapsulate` on the corresponding public key.
687    ///
688    /// :raises ValueError: if this key is not an ML-KEM key or decapsulation fails.
689    ///
690    /// ```python,ignore
691    /// shared_secret = priv.kem_decapsulate(ciphertext)
692    /// ```
693    fn kem_decapsulate<'py>(
694        &self,
695        py: Python<'py>,
696        ciphertext: &[u8],
697    ) -> PyResult<Bound<'py, PyBytes>> {
698        let ss = self
699            .inner
700            .ml_kem_decapsulate(ciphertext)
701            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
702        Ok(PyBytes::new(py, &ss))
703    }
704
705    /// Sign ``data`` with this private key and return the raw signature bytes.
706    ///
707    /// ``algorithm`` is the hash algorithm used during signing (e.g.
708    /// ``"sha256"`` for RSA PKCS\#1 v1.5 and ECDSA).  For Ed25519, Ed448,
709    /// and ML-DSA keys pass ``None`` (or omit the argument) — no pre-hash is
710    /// used.
711    ///
712    /// ``context`` is the ML-DSA context string (FIPS 204 domain separator).
713    /// It defaults to ``b""`` (empty context, equivalent to omitting the
714    /// context).  Ignored for non-ML-DSA keys.
715    ///
716    /// This method signs arbitrary bytes; it is the caller's responsibility to
717    /// hash the data if required by the algorithm (Ed25519 / Ed448 / ML-DSA
718    /// hash internally and must receive the original message, not a pre-hash).
719    ///
720    /// :raises ValueError: if the algorithm is unknown or signing fails.
721    ///
722    /// ```python,ignore
723    /// priv = synta.PrivateKey.generate_ec("P-256")
724    /// sig  = priv.sign(tbs_der, "sha256")
725    /// priv.public_key.verify_signature(sig, tbs_der, "sha256")
726    ///
727    /// ml_priv = synta.PrivateKey.generate_ml_dsa("ML-DSA-65")
728    /// sig = ml_priv.sign(message, context=b"my-app")
729    /// ml_priv.public_key.verify_signature(sig, message, context=b"my-app")
730    /// ```
731    #[pyo3(signature = (data, algorithm = None, context = None))]
732    fn sign<'py>(
733        &self,
734        py: Python<'py>,
735        data: &[u8],
736        algorithm: Option<&str>,
737        context: Option<&[u8]>,
738    ) -> PyResult<Bound<'py, PyBytes>> {
739        let kt = self.inner.key_type();
740        if matches!(kt, "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87") {
741            let sig = self
742                .inner
743                .sign_ml_dsa_with_context(data, context.unwrap_or(b""))
744                .map_err(|e| PyValueError::new_err(format!("{e}")))?;
745            return Ok(PyBytes::new(py, &sig));
746        }
747        let alg = algorithm.unwrap_or("sha256");
748        let signer = self.inner.as_signer(alg);
749        let sig = signer
750            .sign_tbs_erased(data)
751            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
752        Ok(PyBytes::new(py, &sig))
753    }
754
755    fn __repr__(&self) -> String {
756        let kt = self.inner.key_type();
757        let bits = match kt {
758            "ed25519" | "ed448" | "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87" | "ml-kem-512"
759            | "ml-kem-768" | "ml-kem-1024" => String::new(),
760            _ => self
761                .inner
762                .key_bit_size()
763                .map(|b| format!(", key_size={b}"))
764                .unwrap_or_default(),
765        };
766        format!("PrivateKey(key_type={kt:?}{bits})")
767    }
768}
769
770// ── PrivateKey trait impl ─────────────────────────────────────────────────────
771
772/// Implement the backend-agnostic [`synta_certificate::PrivateKey`] trait for
773/// [`PyPrivateKey`] by delegating to [`synta_certificate::BackendPrivateKey`].
774///
775/// This allows Python binding code (e.g. `cert_builder.rs`) to call
776/// `key.as_signer(algorithm)` without importing backend-specific types.
777impl synta_certificate::PrivateKey for PyPrivateKey {
778    fn public_key_spki_der(&self) -> Result<Vec<u8>, synta_certificate::PrivateKeyError> {
779        self.inner.public_key_spki_der()
780    }
781
782    fn as_signer(&self, algorithm: &str) -> Box<dyn synta_certificate::ErasedCertificateSigner> {
783        self.inner.as_signer(algorithm)
784    }
785}