synta-python 0.1.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
//! 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, KeyDecryptor, KeyEncryptor};

// ── 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 })
    }

    /// 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>> {
        use synta_certificate::OpensslRsaOaepEncryptor;
        let ct = OpensslRsaOaepEncryptor::new(self.inner.spki_der(), hash_algorithm)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?
            .encrypt_key(plaintext)
            .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>> {
        use synta_certificate::OpensslRsaPkcs1Encryptor;
        let ct = OpensslRsaPkcs1Encryptor::new(self.inner.spki_der())
            .map_err(|e| PyValueError::new_err(format!("{e}")))?
            .encrypt_key(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 and
    /// Ed448 keys pass ``None`` (or omit the argument) — no pre-hash is used.
    ///
    /// 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
    /// ```
    #[pyo3(signature = (signature, data, algorithm = None))]
    fn verify_signature(
        &self,
        signature: &[u8],
        data: &[u8],
        algorithm: Option<&str>,
    ) -> PyResult<()> {
        self.inner
            .verify_message(data, signature, algorithm)
            .map_err(|e| PyValueError::new_err(format!("{e}")))
    }

    fn __repr__(&self) -> String {
        let kt = self.inner.key_type();
        let bits = match kt {
            "ed25519" | "ed448" => 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 })
    }

    /// 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>> {
        use synta_certificate::OpensslRsaOaepDecryptor;
        let pkcs8 = self
            .inner
            .to_der()
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        let pt = OpensslRsaOaepDecryptor::new(&pkcs8, hash_algorithm)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?
            .decrypt_key(ciphertext)
            .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>> {
        use synta_certificate::OpensslRsaPkcs1Decryptor;
        let pkcs8 = self
            .inner
            .to_der()
            .map_err(|e| PyValueError::new_err(format!("{e}")))?;
        let pt = OpensslRsaPkcs1Decryptor::new(&pkcs8)
            .map_err(|e| PyValueError::new_err(format!("{e}")))?
            .decrypt_key(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 })
    }

    fn __repr__(&self) -> String {
        let kt = self.inner.key_type();
        let bits = match kt {
            "ed25519" | "ed448" => 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)
    }
}