synta-python 0.3.1

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
//! Python bindings for RFC 3279 algorithm parameter types.
//!
//! Exposes ``DssParms``, ``DssSigValue``, ``EcdsaSigValue``, and ``ECParameters``
//! as Python classes, along with the OID constants from the ``PKIXAlgs`` module.
//! All types are installed into the ``synta.pkixalgs`` submodule.

use std::sync::OnceLock;

use pyo3::prelude::*;
use pyo3::types::PyBytes;

use synta::{Decoder, Encoding};

use crate::error::SyntaErr;
use crate::types::PyObjectIdentifier;

// ── PyDssParms ────────────────────────────────────────────────────────────────

/// DSA domain parameters (RFC 3279 §2.3.2).
///
/// Carries the prime modulus ``p``, prime divisor ``q``, and generator ``g``
/// parameters for a DSA public key.  Decoded from the ``parameters`` field
/// of an ``AlgorithmIdentifier`` whose OID is ``id-dsa``.
///
/// ```python,ignore
/// import synta.pkixalgs as pa
/// parms = pa.DssParms.from_der(alg_id_params_der)
/// print(len(parms.p))  # byte length of p
/// ```
#[pyclass(frozen, name = "DssParms")]
pub struct PyDssParms {
    inner: synta_certificate::pkixalgs_types::DssParms,
}

#[pymethods]
impl PyDssParms {
    /// Parse a DER-encoded ``Dss-Parms`` SEQUENCE.
    ///
    /// :param data: DER bytes of the ``Dss-Parms`` SEQUENCE.
    /// :raises ValueError: if the bytes cannot be decoded.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let mut dec = Decoder::new(data, Encoding::Der);
        let inner = dec
            .decode::<synta_certificate::pkixalgs_types::DssParms>()
            .map_err(SyntaErr)?;
        Ok(Self { inner })
    }

    /// Return the DER encoding of this ``Dss-Parms`` SEQUENCE.
    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        Ok(PyBytes::new(py, &self.inner.to_der().map_err(SyntaErr)?))
    }

    /// Prime modulus ``p`` (big-endian two's-complement bytes).
    #[getter]
    fn p<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, self.inner.p.as_bytes())
    }

    /// Prime divisor ``q`` (big-endian two's-complement bytes).
    #[getter]
    fn q<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, self.inner.q.as_bytes())
    }

    /// Generator ``g`` (big-endian two's-complement bytes).
    #[getter]
    fn g<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, self.inner.g.as_bytes())
    }

    fn __repr__(&self) -> String {
        format!(
            "DssParms(p=<{} bytes>, q=<{} bytes>, g=<{} bytes>)",
            self.inner.p.as_bytes().len(),
            self.inner.q.as_bytes().len(),
            self.inner.g.as_bytes().len(),
        )
    }
}

// ── PyDssSigValue ─────────────────────────────────────────────────────────────

/// DSA signature value (RFC 3279 §2.2.2).
///
/// Contains the integer pair ``(r, s)`` produced by the DSA signing operation.
#[pyclass(frozen, name = "DssSigValue")]
pub struct PyDssSigValue {
    inner: synta_certificate::pkixalgs_types::DssSigValue,
}

#[pymethods]
impl PyDssSigValue {
    /// Parse a DER-encoded ``Dss-Sig-Value`` SEQUENCE.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let mut dec = Decoder::new(data, Encoding::Der);
        let inner = dec
            .decode::<synta_certificate::pkixalgs_types::DssSigValue>()
            .map_err(SyntaErr)?;
        Ok(Self { inner })
    }

    /// Return the DER encoding of this ``Dss-Sig-Value`` SEQUENCE.
    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        Ok(PyBytes::new(py, &self.inner.to_der().map_err(SyntaErr)?))
    }

    /// Signature integer ``r`` (big-endian two's-complement bytes).
    #[getter]
    fn r<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, self.inner.r.as_bytes())
    }

    /// Signature integer ``s`` (big-endian two's-complement bytes).
    #[getter]
    fn s<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, self.inner.s.as_bytes())
    }

    fn __repr__(&self) -> String {
        format!(
            "DssSigValue(r=<{} bytes>, s=<{} bytes>)",
            self.inner.r.as_bytes().len(),
            self.inner.s.as_bytes().len(),
        )
    }
}

// ── PyEcdsaSigValue ───────────────────────────────────────────────────────────

/// ECDSA signature value (RFC 3279 §2.2.3, X9.62).
///
/// Contains the integer pair ``(r, s)`` produced by the ECDSA signing
/// operation.  Typically found as the ``subjectPublicKey`` bit-string content
/// inside an X.509 certificate's ``AlgorithmIdentifier`` for ECDSA.
///
/// ```python,ignore
/// import synta.pkixalgs as pa
/// sig = pa.EcdsaSigValue.from_der(signature_bytes)
/// r_bytes, s_bytes = sig.r, sig.s
/// ```
#[pyclass(frozen, name = "EcdsaSigValue")]
pub struct PyEcdsaSigValue {
    inner: synta_certificate::pkixalgs_types::EcdsaSigValue,
}

#[pymethods]
impl PyEcdsaSigValue {
    /// Parse a DER-encoded ``ECDSA-Sig-Value`` SEQUENCE.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let mut dec = Decoder::new(data, Encoding::Der);
        let inner = dec
            .decode::<synta_certificate::pkixalgs_types::EcdsaSigValue>()
            .map_err(SyntaErr)?;
        Ok(Self { inner })
    }

    /// Return the DER encoding of this ``ECDSA-Sig-Value`` SEQUENCE.
    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        Ok(PyBytes::new(py, &self.inner.to_der().map_err(SyntaErr)?))
    }

    /// Signature integer ``r`` (big-endian two's-complement bytes).
    #[getter]
    fn r<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, self.inner.r.as_bytes())
    }

    /// Signature integer ``s`` (big-endian two's-complement bytes).
    #[getter]
    fn s<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, self.inner.s.as_bytes())
    }

    fn __repr__(&self) -> String {
        format!(
            "EcdsaSigValue(r=<{} bytes>, s=<{} bytes>)",
            self.inner.r.as_bytes().len(),
            self.inner.s.as_bytes().len(),
        )
    }
}

// ── PyECParameters ────────────────────────────────────────────────────────────

/// EC domain parameters (RFC 3279 §2.3.5, X9.62).
///
/// A CHOICE with three alternatives:
///
/// * ``namedCurve`` — an OID identifying a well-known curve (most common in X.509)
/// * ``ecParameters`` — explicit ``SpecifiedECDomain`` (rarely used in PKI)
/// * ``implicitlyCA`` — NULL (inherit parameters from the CA certificate)
///
/// Use :attr:`arm` to determine which alternative is present, and
/// :attr:`named_curve_oid` to obtain the OID for the ``namedCurve`` arm.
///
/// ```python,ignore
/// import synta.pkixalgs as pa
/// params = pa.ECParameters.from_der(alg_params_der)
/// if params.arm == "namedCurve":
///     print(params.named_curve_oid)
/// ```
#[pyclass(frozen, name = "ECParameters")]
pub struct PyECParameters {
    _data: Py<PyBytes>,
    raw: &'static [u8],
    inner: OnceLock<Box<synta_certificate::pkixalgs_types::ECParameters<'static>>>,
}

impl PyECParameters {
    fn params(&self) -> PyResult<&synta_certificate::pkixalgs_types::ECParameters<'static>> {
        if let Some(v) = self.inner.get() {
            return Ok(v.as_ref());
        }
        let mut dec = Decoder::new(self.raw, Encoding::Der);
        let decoded = dec
            .decode::<synta_certificate::pkixalgs_types::ECParameters<'static>>()
            .map_err(SyntaErr)?;
        let _ = self.inner.set(Box::new(decoded));
        Ok(self.inner.get().unwrap().as_ref())
    }
}

#[pymethods]
impl PyECParameters {
    /// Parse a DER-encoded ``ECParameters`` CHOICE.
    #[staticmethod]
    fn from_der(py: Python<'_>, data: Bound<'_, PyBytes>) -> PyResult<Self> {
        let py_bytes = data.unbind();
        // Validate before storing
        {
            let raw = py_bytes.as_bytes(py);
            Decoder::new(raw, Encoding::Der)
                .decode::<synta_certificate::pkixalgs_types::ECParameters<'_>>()
                .map_err(SyntaErr)?;
        }
        let raw: &'static [u8] = unsafe {
            let s = py_bytes.bind(py).as_bytes();
            std::slice::from_raw_parts(s.as_ptr(), s.len())
        };
        Ok(Self {
            _data: py_bytes,
            raw,
            inner: OnceLock::new(),
        })
    }

    /// Return the DER encoding of this ``ECParameters`` value.
    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        Ok(PyBytes::new(
            py,
            &self.params()?.to_der().map_err(SyntaErr)?,
        ))
    }

    /// Which CHOICE arm is present: ``"namedCurve"``, ``"ecParameters"``, or
    /// ``"implicitlyCA"``.
    #[getter]
    fn arm(&self) -> PyResult<&'static str> {
        use synta_certificate::pkixalgs_types::ECParameters::*;
        Ok(match self.params()? {
            NamedCurve(_) => "namedCurve",
            EcParameters(_) => "ecParameters",
            ImplicitlyCA(_) => "implicitlyCA",
        })
    }

    /// The named-curve OID, or ``None`` if the arm is not ``namedCurve``.
    #[getter]
    fn named_curve_oid(&self, py: Python<'_>) -> PyResult<Option<Py<PyObjectIdentifier>>> {
        use synta_certificate::pkixalgs_types::ECParameters::*;
        match self.params()? {
            NamedCurve(oid) => {
                let obj = Py::new(py, PyObjectIdentifier::from_oid(oid.clone()))?;
                Ok(Some(obj))
            }
            _ => Ok(None),
        }
    }

    fn __repr__(&self) -> PyResult<String> {
        Ok(format!("ECParameters(arm={})", self.arm()?))
    }
}

// ── PyAlgorithmIdentifier ─────────────────────────────────────────────────────

/// An X.509 ``AlgorithmIdentifier`` SEQUENCE (RFC 5280 §4.1.1.2).
///
/// Wraps an algorithm OID and optional parameters as a pre-encoded DER
/// SEQUENCE.  Use :meth:`to_der` to obtain bytes ready for passing to builder
/// APIs such as :meth:`~synta.CertificateListBuilder.signature_algorithm`.
///
/// Two constructors handle the two conventions used in practice:
///
/// * :meth:`from_oid` — RSA-family algorithms; encodes ``SEQUENCE { oid, NULL }``
/// * :meth:`from_oid_no_params` — ECDSA/EdDSA; encodes ``SEQUENCE { oid }``
///
/// ```python,ignore
/// import synta
/// alg = synta.AlgorithmIdentifier.from_oid(synta.oids.SHA256_WITH_RSA)
/// crl_builder.signature_algorithm(alg.to_der())
/// ```
#[pyclass(frozen, name = "AlgorithmIdentifier")]
pub struct PyAlgorithmIdentifier {
    der: Vec<u8>,
    oid: synta::ObjectIdentifier,
}

impl PyAlgorithmIdentifier {
    fn build(oid: synta::ObjectIdentifier, with_null: bool) -> PyResult<Self> {
        // Encode inner content: OID [+ NULL]
        let mut inner_enc = synta::Encoder::new(Encoding::Der);
        inner_enc.encode(&oid).map_err(SyntaErr)?;
        if with_null {
            inner_enc.encode(&synta::Null).map_err(SyntaErr)?;
        }
        let inner = inner_enc.finish().map_err(SyntaErr)?;

        // Wrap in SEQUENCE { ... }
        let mut outer_enc = synta::Encoder::new(Encoding::Der);
        outer_enc
            .write_tag(synta::Tag::universal_constructed(synta::tag::TAG_SEQUENCE))
            .map_err(SyntaErr)?;
        outer_enc.write_length(inner.len()).map_err(SyntaErr)?;
        outer_enc.write_bytes(&inner);
        let der = outer_enc.finish().map_err(SyntaErr)?;

        Ok(Self { der, oid })
    }
}

#[pymethods]
impl PyAlgorithmIdentifier {
    /// Construct an ``AlgorithmIdentifier`` with an explicit ``NULL`` parameters field.
    ///
    /// Required for RSA-family signature algorithms (``sha256WithRSAEncryption``,
    /// ``sha384WithRSAEncryption``, etc.) per RFC 3279 §2.2.1.
    ///
    /// :param oid: Algorithm :class:`~synta.ObjectIdentifier`.
    #[staticmethod]
    fn from_oid(oid: &PyObjectIdentifier) -> PyResult<Self> {
        Self::build(oid.inner.clone(), true)
    }

    /// Construct an ``AlgorithmIdentifier`` without a parameters field.
    ///
    /// Used for ECDSA and EdDSA algorithms, which omit the parameters
    /// field entirely per RFC 3279 §2.2.3 and RFC 8410.
    ///
    /// :param oid: Algorithm :class:`~synta.ObjectIdentifier`.
    #[staticmethod]
    fn from_oid_no_params(oid: &PyObjectIdentifier) -> PyResult<Self> {
        Self::build(oid.inner.clone(), false)
    }

    /// Return the DER encoding of the complete ``AlgorithmIdentifier`` SEQUENCE.
    ///
    /// :returns: DER bytes suitable for
    ///     :meth:`~synta.CertificateListBuilder.signature_algorithm` and
    ///     similar builder methods.
    fn to_der<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.der)
    }

    /// The algorithm OID.
    #[getter]
    fn oid(&self, py: Python<'_>) -> PyResult<Py<PyObjectIdentifier>> {
        Py::new(py, PyObjectIdentifier::from_oid(self.oid.clone()))
    }

    fn __repr__(&self) -> String {
        format!("AlgorithmIdentifier({})", self.oid)
    }
}

// ── register_pkixalgs_submodule ───────────────────────────────────────────────

/// Build and register the ``synta.pkixalgs`` submodule.
pub(super) fn register_pkixalgs_submodule(parent: &Bound<'_, PyModule>) -> PyResult<()> {
    let py = parent.py();
    let m = PyModule::new(py, "pkixalgs")?;

    m.add_class::<PyAlgorithmIdentifier>()?;
    m.add_class::<PyDssParms>()?;
    m.add_class::<PyDssSigValue>()?;
    m.add_class::<PyEcdsaSigValue>()?;
    m.add_class::<PyECParameters>()?;

    // ── DSA / DH OIDs ────────────────────────────────────────────────────────
    m.add(
        "ID_DSA",
        super::oid_const(py, synta_certificate::pkixalgs_types::ID_DSA),
    )?;
    m.add(
        "ID_DSA_WITH_SHA1",
        super::oid_const(py, synta_certificate::pkixalgs_types::ID_DSA_WITH_SHA1),
    )?;
    m.add(
        "DHPUBLICNUMBER",
        super::oid_const(py, synta_certificate::pkixalgs_types::DHPUBLICNUMBER),
    )?;

    // ── EC / ECDSA OIDs ──────────────────────────────────────────────────────
    m.add(
        "ID_EC_PUBLIC_KEY",
        super::oid_const(py, synta_certificate::pkixalgs_types::ID_EC_PUBLIC_KEY),
    )?;
    m.add(
        "ECDSA_WITH_SHA1",
        super::oid_const(py, synta_certificate::pkixalgs_types::ECDSA_WITH_SHA1),
    )?;
    m.add(
        "ECDSA_WITH_SHA256",
        super::oid_const(py, synta_certificate::pkixalgs_types::ECDSA_WITH_SHA256),
    )?;
    m.add(
        "ECDSA_WITH_SHA384",
        super::oid_const(py, synta_certificate::pkixalgs_types::ECDSA_WITH_SHA384),
    )?;
    m.add(
        "ECDSA_WITH_SHA512",
        super::oid_const(py, synta_certificate::pkixalgs_types::ECDSA_WITH_SHA512),
    )?;

    // ── Named curve OIDs ─────────────────────────────────────────────────────
    m.add(
        "PRIME192V1",
        super::oid_const(py, synta_certificate::pkixalgs_types::PRIME192V1),
    )?;
    m.add(
        "PRIME256V1",
        super::oid_const(py, synta_certificate::pkixalgs_types::PRIME256V1),
    )?;
    m.add(
        "SECP224R1",
        super::oid_const(py, synta_certificate::pkixalgs_types::SECP224R1),
    )?;
    m.add(
        "SECP384R1",
        super::oid_const(py, synta_certificate::pkixalgs_types::SECP384R1),
    )?;
    m.add(
        "SECP521R1",
        super::oid_const(py, synta_certificate::pkixalgs_types::SECP521R1),
    )?;

    crate::install_submodule(
        parent,
        &m,
        "synta.pkixalgs",
        Some(concat!(
            "synta.pkixalgs — RFC 3279 algorithm parameter types.\n\n",
            "Provides DssParms, DssSigValue, EcdsaSigValue, and ECParameters\n",
            "for decoding DSA/DH domain parameters and DSA/ECDSA signature values,\n",
            "along with OID constants for DSA, DH, EC, and named-curve algorithms.",
        )),
    )
}