_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 /// Load a private key from a PKCS#11 URI (RFC 7512).
517 ///
518 /// Requires the OpenSSL PKCS#11 provider or NSS to be configured.
519 /// The URI has the form ``pkcs11:token=MyToken;id=%01%02%03;pin-value=1234``.
520 ///
521 /// Raises :exc:`ValueError` if the URI cannot be parsed or the key cannot be loaded.
522 #[staticmethod]
523 #[cfg(any(feature = "openssl", feature = "nss"))]
524 fn from_pkcs11_uri(uri: &str) -> PyResult<Self> {
525 let inner = BackendPrivateKey::from_pkcs11_uri(uri)
526 .map_err(|e| PyValueError::new_err(format!("{e}")))?;
527 Ok(Self { inner })
528 }
529
530 /// The key algorithm as a lowercase string.
531 ///
532 /// Returns one of ``"rsa"``, ``"ec"``, ``"ed25519"``, ``"ed448"``,
533 /// ``"dsa"``, or ``"unknown"``.
534 #[getter]
535 fn key_type(&self) -> &'static str {
536 self.inner.key_type()
537 }
538
539 /// The key size in bits, or ``None`` for EdDSA keys.
540 #[getter]
541 fn key_size(&self) -> Option<i64> {
542 self.inner.key_bit_size()
543 }
544
545 /// The public key corresponding to this private key.
546 ///
547 /// ```python,ignore
548 /// pub = priv.public_key
549 /// ct = pub.rsa_oaep_encrypt(b"data", "sha256")
550 /// ```
551 #[getter]
552 fn public_key(&self) -> PyResult<PyPublicKey> {
553 let bpk = self
554 .inner
555 .public_key()
556 .map_err(|e| PyValueError::new_err(format!("{e}")))?;
557 Ok(PyPublicKey { inner: bpk })
558 }
559
560 /// Decrypt ``ciphertext`` with RSA-OAEP using the specified hash algorithm.
561 ///
562 /// ``hash_algorithm`` must be one of ``"sha1"``, ``"sha224"``,
563 /// ``"sha256"``, ``"sha384"``, or ``"sha512"``.
564 ///
565 /// Raises :exc:`ValueError` if this key is not an RSA key.
566 ///
567 /// ```python,ignore
568 /// plaintext = priv.rsa_oaep_decrypt(ciphertext, "sha256")
569 /// ```
570 #[pyo3(signature = (ciphertext, hash_algorithm = "sha256"))]
571 fn rsa_oaep_decrypt<'py>(
572 &self,
573 py: Python<'py>,
574 ciphertext: &[u8],
575 hash_algorithm: &str,
576 ) -> PyResult<Bound<'py, PyBytes>> {
577 let pt = self
578 .inner
579 .rsa_oaep_decrypt(ciphertext, hash_algorithm)
580 .map_err(|e| PyValueError::new_err(format!("{e}")))?;
581 Ok(PyBytes::new(py, &pt))
582 }
583
584 /// Decrypt ``ciphertext`` with RSA PKCS\#1 v1.5 padding.
585 ///
586 /// Raises :exc:`ValueError` if this key is not an RSA key.
587 ///
588 /// ```python,ignore
589 /// plaintext = priv.rsa_pkcs1v15_decrypt(ciphertext)
590 /// ```
591 fn rsa_pkcs1v15_decrypt<'py>(
592 &self,
593 py: Python<'py>,
594 ciphertext: &[u8],
595 ) -> PyResult<Bound<'py, PyBytes>> {
596 let pt = self
597 .inner
598 .rsa_pkcs1v15_decrypt(ciphertext)
599 .map_err(|e| PyValueError::new_err(format!("{e}")))?;
600 Ok(PyBytes::new(py, &pt))
601 }
602
603 /// Generate a new RSA private key.
604 ///
605 /// ``key_size`` is the modulus bit-length (e.g. 2048, 3072, 4096).
606 /// ``public_exponent`` defaults to 65537.
607 ///
608 /// ```python,ignore
609 /// priv = synta.PrivateKey.generate_rsa(2048)
610 /// ```
611 #[staticmethod]
612 #[pyo3(signature = (key_size, public_exponent = 65537))]
613 fn generate_rsa(key_size: u32, public_exponent: u32) -> PyResult<Self> {
614 let inner = BackendPrivateKey::generate_rsa(key_size, public_exponent)
615 .map_err(|e| PyValueError::new_err(format!("{e}")))?;
616 Ok(Self { inner })
617 }
618
619 /// Generate a new EC private key on the specified named curve.
620 ///
621 /// ``curve`` must be one of ``"P-256"``, ``"P-384"``, or ``"P-521"``.
622 /// Raises :exc:`ValueError` for unknown curve names.
623 ///
624 /// ```python,ignore
625 /// priv = synta.PrivateKey.generate_ec("P-256")
626 /// ```
627 #[staticmethod]
628 #[pyo3(signature = (curve = "P-256"))]
629 fn generate_ec(curve: &str) -> PyResult<Self> {
630 let inner = BackendPrivateKey::generate_ec(curve)
631 .map_err(|e| PyValueError::new_err(format!("{e}")))?;
632 Ok(Self { inner })
633 }
634
635 /// Generate a new Ed25519 private key (RFC 8032).
636 ///
637 /// ```python,ignore
638 /// priv = synta.PrivateKey.generate_ed25519()
639 /// pub = priv.public_key
640 /// ```
641 #[staticmethod]
642 fn generate_ed25519() -> PyResult<Self> {
643 let inner = BackendPrivateKey::generate_ed25519()
644 .map_err(|e| PyValueError::new_err(format!("{e}")))?;
645 Ok(Self { inner })
646 }
647
648 /// Generate a new Ed448 private key (RFC 8032).
649 ///
650 /// ```python,ignore
651 /// priv = synta.PrivateKey.generate_ed448()
652 /// pub = priv.public_key
653 /// ```
654 #[staticmethod]
655 fn generate_ed448() -> PyResult<Self> {
656 let inner = BackendPrivateKey::generate_ed448()
657 .map_err(|e| PyValueError::new_err(format!("{e}")))?;
658 Ok(Self { inner })
659 }
660
661 /// Generate a new ML-DSA private key (FIPS 204).
662 ///
663 /// ``parameter_set`` must be one of ``"ML-DSA-44"``, ``"ML-DSA-65"``, or
664 /// ``"ML-DSA-87"``. Requires OpenSSL 3.5 or newer.
665 ///
666 /// ```python,ignore
667 /// priv = synta.PrivateKey.generate_ml_dsa("ML-DSA-65")
668 /// pub = priv.public_key
669 /// sig = priv.sign(message)
670 /// ```
671 #[staticmethod]
672 fn generate_ml_dsa(parameter_set: &str) -> PyResult<Self> {
673 let inner = BackendPrivateKey::generate_ml_dsa(parameter_set)
674 .map_err(|e| PyValueError::new_err(format!("{e}")))?;
675 Ok(Self { inner })
676 }
677
678 /// Generate a new composite ML-DSA private key (draft-ietf-lamps-pq-composite-sigs-19).
679 ///
680 /// ``sub_arc`` selects the composite variant by its OID sub-arc (37–54):
681 ///
682 /// | sub_arc | Algorithm |
683 /// |---------|-----------|
684 /// | 37 | MLDSA44-RSA2048-PSS-SHA256 |
685 /// | 38 | MLDSA44-RSA2048-PKCS15-SHA256 |
686 /// | 39 | MLDSA44-Ed25519-SHA512 |
687 /// | 40 | MLDSA44-ECDSA-P256-SHA256 |
688 /// | 41 | MLDSA65-RSA3072-PSS-SHA512 |
689 /// | 42 | MLDSA65-RSA3072-PKCS15-SHA512 |
690 /// | 43 | MLDSA65-RSA4096-PSS-SHA512 |
691 /// | 44 | MLDSA65-RSA4096-PKCS15-SHA512 |
692 /// | 45 | MLDSA65-ECDSA-P256-SHA512 |
693 /// | 46 | MLDSA65-ECDSA-P384-SHA512 |
694 /// | 47 | MLDSA65-ECDSA-brainpoolP256r1-SHA512 |
695 /// | 48 | MLDSA65-Ed25519-SHA512 |
696 /// | 49 | MLDSA87-ECDSA-P384-SHA512 |
697 /// | 50 | MLDSA87-ECDSA-brainpoolP384r1-SHA512 |
698 /// | 51 | MLDSA87-Ed448-SHAKE256 |
699 /// | 52 | MLDSA87-RSA3072-PSS-SHA512 |
700 /// | 53 | MLDSA87-RSA4096-PSS-SHA512 |
701 /// | 54 | MLDSA87-ECDSA-P521-SHA512 |
702 ///
703 /// Requires OpenSSL 3.3+ (with ML-DSA support) and the ``pqc`` Cargo
704 /// feature, or NSS.
705 ///
706 /// ```python,ignore
707 /// # Generate MLDSA65-ECDSA-P256-SHA512 (sub_arc=45)
708 /// priv = synta.PrivateKey.generate_composite_ml_dsa(45)
709 /// ```
710 #[staticmethod]
711 fn generate_composite_ml_dsa(sub_arc: u32) -> PyResult<Self> {
712 let inner = synta_certificate::BackendPrivateKey::generate_composite_ml_dsa(sub_arc)
713 .map_err(|e| PyValueError::new_err(format!("{e}")))?;
714 Ok(Self { inner })
715 }
716
717 /// Generate a new ML-KEM private key (FIPS 203).
718 ///
719 /// ``parameter_set`` must be one of ``"ML-KEM-512"``, ``"ML-KEM-768"``, or
720 /// ``"ML-KEM-1024"``. Requires OpenSSL 3.5 or newer.
721 ///
722 /// ```python,ignore
723 /// priv = synta.PrivateKey.generate_ml_kem("ML-KEM-768")
724 /// pub = priv.public_key
725 /// ct, ss = pub.kem_encapsulate()
726 /// ss2 = priv.kem_decapsulate(ct)
727 /// assert ss == ss2
728 /// ```
729 #[staticmethod]
730 fn generate_ml_kem(parameter_set: &str) -> PyResult<Self> {
731 let inner = BackendPrivateKey::generate_ml_kem(parameter_set)
732 .map_err(|e| PyValueError::new_err(format!("{e}")))?;
733 Ok(Self { inner })
734 }
735
736 /// ML-KEM decapsulation: recover the shared secret from ``ciphertext``.
737 ///
738 /// The ``ciphertext`` must have been produced by the peer calling
739 /// :meth:`PublicKey.kem_encapsulate` on the corresponding public key.
740 ///
741 /// :raises ValueError: if this key is not an ML-KEM key or decapsulation fails.
742 ///
743 /// ```python,ignore
744 /// shared_secret = priv.kem_decapsulate(ciphertext)
745 /// ```
746 fn kem_decapsulate<'py>(
747 &self,
748 py: Python<'py>,
749 ciphertext: &[u8],
750 ) -> PyResult<Bound<'py, PyBytes>> {
751 let ss = self
752 .inner
753 .ml_kem_decapsulate(ciphertext)
754 .map_err(|e| PyValueError::new_err(format!("{e}")))?;
755 Ok(PyBytes::new(py, &ss))
756 }
757
758 /// Sign ``data`` with this private key and return the raw signature bytes.
759 ///
760 /// ``algorithm`` is the hash algorithm used during signing (e.g.
761 /// ``"sha256"`` for RSA PKCS\#1 v1.5 and ECDSA). For Ed25519, Ed448,
762 /// and ML-DSA keys pass ``None`` (or omit the argument) — no pre-hash is
763 /// used.
764 ///
765 /// ``context`` is the ML-DSA context string (FIPS 204 domain separator).
766 /// It defaults to ``b""`` (empty context, equivalent to omitting the
767 /// context). Ignored for non-ML-DSA keys.
768 ///
769 /// This method signs arbitrary bytes; it is the caller's responsibility to
770 /// hash the data if required by the algorithm (Ed25519 / Ed448 / ML-DSA
771 /// hash internally and must receive the original message, not a pre-hash).
772 ///
773 /// :raises ValueError: if the algorithm is unknown or signing fails.
774 ///
775 /// ```python,ignore
776 /// priv = synta.PrivateKey.generate_ec("P-256")
777 /// sig = priv.sign(tbs_der, "sha256")
778 /// priv.public_key.verify_signature(sig, tbs_der, "sha256")
779 ///
780 /// ml_priv = synta.PrivateKey.generate_ml_dsa("ML-DSA-65")
781 /// sig = ml_priv.sign(message, context=b"my-app")
782 /// ml_priv.public_key.verify_signature(sig, message, context=b"my-app")
783 /// ```
784 #[pyo3(signature = (data, algorithm = None, context = None))]
785 fn sign<'py>(
786 &self,
787 py: Python<'py>,
788 data: &[u8],
789 algorithm: Option<&str>,
790 context: Option<&[u8]>,
791 ) -> PyResult<Bound<'py, PyBytes>> {
792 let kt = self.inner.key_type();
793 if matches!(kt, "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87") {
794 let sig = self
795 .inner
796 .sign_ml_dsa_with_context(data, context.unwrap_or(b""))
797 .map_err(|e| PyValueError::new_err(format!("{e}")))?;
798 return Ok(PyBytes::new(py, &sig));
799 }
800 let alg = algorithm.unwrap_or("sha256");
801 let signer = self.inner.as_signer(alg);
802 let sig = signer
803 .sign_tbs_erased(data)
804 .map_err(|e| PyValueError::new_err(format!("{e}")))?;
805 Ok(PyBytes::new(py, &sig))
806 }
807
808 fn __repr__(&self) -> String {
809 let kt = self.inner.key_type();
810 let bits = match kt {
811 "ed25519" | "ed448" | "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87" | "ml-kem-512"
812 | "ml-kem-768" | "ml-kem-1024" => String::new(),
813 _ => self
814 .inner
815 .key_bit_size()
816 .map(|b| format!(", key_size={b}"))
817 .unwrap_or_default(),
818 };
819 format!("PrivateKey(key_type={kt:?}{bits})")
820 }
821}
822
823// ── PrivateKey trait impl ─────────────────────────────────────────────────────
824
825/// Implement the backend-agnostic [`synta_certificate::PrivateKey`] trait for
826/// [`PyPrivateKey`] by delegating to [`synta_certificate::BackendPrivateKey`].
827///
828/// This allows Python binding code (e.g. `cert_builder.rs`) to call
829/// `key.as_signer(algorithm)` without importing backend-specific types.
830impl synta_certificate::PrivateKey for PyPrivateKey {
831 fn public_key_spki_der(&self) -> Result<Vec<u8>, synta_certificate::PrivateKeyError> {
832 self.inner.public_key_spki_der()
833 }
834
835 fn as_signer(&self, algorithm: &str) -> Box<dyn synta_certificate::ErasedCertificateSigner> {
836 self.inner.as_signer(algorithm)
837 }
838}