synta-python 0.2.5

Python extension module for the synta ASN.1 library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
//! Python bindings for Synta ASN.1 library
//!
//! This module provides PyO3-based Python bindings for the Synta ASN.1 library,
//! enabling high-performance ASN.1 parsing and encoding from Python.

// Python binding doc comments use RST-style `Example::` + indented code blocks
// (the format familiar to Python developers).  Rustdoc parses these indented
// blocks as Rust code and warns when they cannot be compiled.  Suppress that
// diagnostic for the whole crate since the examples are intentionally Python.
#![allow(rustdoc::invalid_rust_codeblocks)]

use pyo3::prelude::*;

pub mod certificate;
pub mod crypto;
pub mod crypto_keys;
pub mod decoder;
pub mod encoder;
pub mod error;
pub mod ext_builders;
pub mod otp;
#[cfg(feature = "pkcs11-mgmt")]
pub mod pkcs11;
pub mod types;
pub mod x509_verification;

// Re-export for convenience
pub use certificate::*;
pub use decoder::*;
pub use encoder::*;
pub use error::*;
pub use types::*;

// Re-export from common crate for use by all submodules in this crate.
pub(crate) use synta_python_common::install_submodule;

/// ASN.1 encoding rules
///
/// Specifies which encoding rules to use when encoding or decoding ASN.1 data.
#[pyclass(name = "Encoding")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PyEncoding {
    /// Distinguished Encoding Rules (deterministic subset of BER)
    DER,
    /// Basic Encoding Rules (most flexible)
    BER,
    /// Canonical Encoding Rules (similar to DER but for streaming)
    CER,
}

impl From<PyEncoding> for synta::Encoding {
    fn from(enc: PyEncoding) -> Self {
        match enc {
            PyEncoding::DER => synta::Encoding::Der,
            PyEncoding::BER => synta::Encoding::Ber,
            PyEncoding::CER => synta::Encoding::Cer,
        }
    }
}

impl From<synta::Encoding> for PyEncoding {
    fn from(enc: synta::Encoding) -> Self {
        match enc {
            synta::Encoding::Der => PyEncoding::DER,
            synta::Encoding::Ber => PyEncoding::BER,
            synta::Encoding::Cer => PyEncoding::CER,
        }
    }
}

/// Synta: High-performance ASN.1 parser and encoder
///
/// This module provides ASN.1 parsing, decoding, and encoding capabilities
/// with support for DER (Distinguished Encoding Rules) and BER (Basic Encoding Rules).
///
/// Example:
///     >>> import synta
///     >>> # Decode an integer
///     >>> decoder = synta.Decoder(b'\\x02\\x01\\x2A', synta.Encoding.DER)
///     >>> integer = decoder.decode_integer()
///     >>> print(integer.to_int())
///     42
#[pymodule]
fn _synta(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
    // Add encoding enum
    m.add_class::<PyEncoding>()?;

    // Add error types
    m.add("SyntaError", py.get_type::<SyntaError>())?;

    // Add decoder and encoder
    m.add_class::<PyDecoder>()?;
    m.add_class::<PyEncoder>()?;

    // Add primitive types
    m.add_class::<PyInteger>()?;
    m.add_class::<PyOctetString>()?;
    m.add_class::<PyBitString>()?;
    m.add_class::<PyBoolean>()?;
    m.add_class::<PyReal>()?;
    m.add_class::<PyUtcTime>()?;
    m.add_class::<PyGeneralizedTime>()?;
    m.add_class::<PyNull>()?;
    m.add_class::<PyUtf8String>()?;
    m.add_class::<PyPrintableString>()?;
    m.add_class::<PyIA5String>()?;
    // New string types
    m.add_class::<PyNumericString>()?;
    m.add_class::<PyTeletexString>()?;
    m.add_class::<PyVisibleString>()?;
    m.add_class::<PyGeneralString>()?;
    m.add_class::<PyUniversalString>()?;
    m.add_class::<PyBmpString>()?;
    m.add_class::<PyTaggedElement>()?;
    m.add_class::<PyRawElement>()?;

    // Add certificate types (Certificate, CertificationRequest, CertificateList, OCSPResponse)
    // and the pem_to_der helper function.
    certificate::register_module(m)?;
    m.add_function(wrap_pyfunction!(pem_to_der, m)?)?;
    m.add_function(wrap_pyfunction!(der_to_pem, m)?)?;
    m.add_function(wrap_pyfunction!(parse_general_names, m)?)?;
    m.add_function(wrap_pyfunction!(parse_name_attrs, m)?)?;
    m.add_function(wrap_pyfunction!(encode_extended_key_usage, m)?)?;
    m.add_function(wrap_pyfunction!(encode_subject_alt_names, m)?)?;
    m.add_function(wrap_pyfunction!(name_der_equal, m)?)?;
    m.add_function(wrap_pyfunction!(digest, m)?)?;
    m.add_function(wrap_pyfunction!(format_dn, m)?)?;
    m.add_function(wrap_pyfunction!(format_dn_slash, m)?)?;
    m.add_function(wrap_pyfunction!(find_extension_value, m)?)?;
    m.add_function(wrap_pyfunction!(encode_general_names, m)?)?;
    m.add_function(wrap_pyfunction!(signing_algorithm_der, m)?)?;
    m.add_function(wrap_pyfunction!(key_usage_bit, m)?)?;
    m.add_function(wrap_pyfunction!(decode_public_key_info, m)?)?;

    // PublicKey and PrivateKey classes
    m.add_class::<crypto_keys::PyPublicKey>()?;
    m.add_class::<crypto_keys::PyPrivateKey>()?;

    // Symmetric crypto submodule (synta.crypto)
    crypto::register_crypto_module(m)?;

    // X.509 extension value builders submodule (synta.ext)
    ext_builders::register_ext_module(m)?;

    // X.509 verification submodule (synta.x509)
    x509_verification::register_x509_module(m)?;

    // PKCS#11 token management submodule (synta.pkcs11)
    #[cfg(feature = "pkcs11-mgmt")]
    pkcs11::register_pkcs11_module(m)?;

    // Add version
    m.add("__version__", env!("CARGO_PKG_VERSION"))?;

    Ok(())
}

/// Parse a DER-encoded GeneralNames SEQUENCE into ``(tag_number, content_bytes)`` pairs.
///
/// ``san_der`` must be the **complete DER bytes** of the ``SEQUENCE OF GeneralName``
/// value — exactly what you get from the SAN extension's ``extn_value`` octet-string
/// content, or from ``Certificate.get_extension_value_der("2.5.29.17")``.
///
/// Returns a ``list`` of ``(tag_number: int, content: bytes)`` tuples, one per
/// ``GeneralName`` alternative.  Tag numbers follow RFC 5280:
///
/// * 0 — otherName (constructed; ``content`` is the full ``OtherNameValue`` TLV)
/// * 1 — rfc822Name (email); ``content`` is raw IA5String bytes
/// * 2 — dNSName; ``content`` is raw IA5String bytes
/// * 3 — x400Address
/// * 4 — directoryName; ``content`` is the Name SEQUENCE TLV — pass to ``parse_name_attrs()``
/// * 5 — ediPartyName
/// * 6 — uniformResourceIdentifier; ``content`` is raw IA5String bytes
/// * 7 — iPAddress; ``content`` is 4 bytes (IPv4) or 16 bytes (IPv6)
/// * 8 — registeredID; ``content`` is raw OID value bytes
///
/// Tag constants are available in the :mod:`synta.general_name` submodule
/// (e.g. ``synta.general_name.DNS_NAME == 2``), making dispatch readable
/// without hardcoded magic numbers:
///
/// ```python,ignore
/// import ipaddress
/// import synta.general_name as gn
///
/// san_der = cert.get_extension_value_der("2.5.29.17")
/// for tag_num, content in synta.parse_general_names(san_der):
///     if tag_num == gn.DNS_NAME:
///         print("DNS:", content.decode("ascii"))
///     elif tag_num == gn.IP_ADDRESS:
///         print("IP:", ipaddress.ip_address(content))
///     elif tag_num == gn.RFC822_NAME:
///         print("email:", content.decode("ascii"))
///     elif tag_num == gn.DIRECTORY_NAME:
///         attrs = synta.parse_name_attrs(content)
///         print("DirName:", attrs)
///     elif tag_num == gn.URI:
///         print("URI:", content.decode("ascii"))
/// ```
///
/// Returns an empty list if ``san_der`` cannot be parsed as a DER SEQUENCE.
#[pyfunction]
fn parse_general_names<'py>(
    py: Python<'py>,
    san_der: &[u8],
) -> PyResult<Bound<'py, pyo3::types::PyList>> {
    use pyo3::types::{PyBytes, PyList, PyTuple};

    let list = PyList::empty(py);
    for (tag_num, content) in synta_certificate::parse_general_names(san_der) {
        let tuple = PyTuple::new(
            py,
            [
                tag_num.into_pyobject(py)?.into_any(),
                PyBytes::new(py, &content).into_any(),
            ],
        )?;
        list.append(tuple)?;
    }
    Ok(list)
}

/// Walk a DER-encoded X.500 Name SEQUENCE and return ``(dotted_oid, value_str)`` pairs.
///
/// ``name_der`` must be the **complete TLV** bytes of the Name SEQUENCE (tag + length
/// + value), as returned by ``Certificate.issuer_raw_der`` or
/// ``Certificate.subject_raw_der``, or from a ``directoryName`` entry in
/// ``parse_general_names()``.
///
/// Returns a ``list`` of ``(oid: str, value: str)`` tuples in DER traversal order
/// (outermost RDN first, innermost ATV first within each RDN).  The OID is always
/// in dotted-decimal notation (e.g. ``"2.5.4.3"``).  The value string is decoded
/// using the appropriate per-tag encoding: UTF-8 for most types, Latin-1 for
/// TeletexString, UCS-2 big-endian for BMPString, and UCS-4 big-endian for
/// UniversalString.
///
/// This replaces manual ``Decoder`` iteration over the Name structure and is the
/// structured-data counterpart to the ``Certificate.issuer`` string property:
///
/// ```python
/// # Inspect subject attributes directly:
/// attrs = synta.parse_name_attrs(cert.subject_raw_der)
/// # → [("2.5.4.6", "US"), ("2.5.4.10", "Example Corp"), ("2.5.4.3", "Root CA")]
///
/// # Build a cryptography.x509.Name for comparison or re-use:
/// from cryptography.x509 import Name, NameAttribute, ObjectIdentifier
/// name = Name([
///     NameAttribute(ObjectIdentifier(oid), val)
///     for oid, val in synta.parse_name_attrs(cert.subject_raw_der)
/// ])
/// ```
///
/// Returns an empty list if ``name_der`` cannot be parsed.
#[pyfunction]
fn parse_name_attrs<'py>(
    py: Python<'py>,
    name_der: &[u8],
) -> PyResult<Bound<'py, pyo3::types::PyList>> {
    use pyo3::types::{PyList, PyTuple};

    let attrs = synta_certificate::name::parse_name_attrs(name_der);
    let list = PyList::empty(py);
    for (oid, value) in attrs {
        let tuple = PyTuple::new(
            py,
            [
                oid.into_pyobject(py)?.into_any(),
                value.into_pyobject(py)?.into_any(),
            ],
        )?;
        list.append(tuple)?;
    }
    Ok(list)
}

/// Encode DER bytes as a PEM block.
///
/// Returns :class:`bytes` containing a ``-----BEGIN {label}-----`` /
/// ``-----END {label}-----`` block with standard 64-character base64 lines.
/// This is the low-level inverse of :func:`pem_to_der`.
///
/// For serialising parsed objects use the class-level
/// ``Certificate.to_pem()``, ``CertificationRequest.to_pem()``, etc., which
/// fill in the correct label automatically.
///
/// ```python
/// with open("cert.der", "rb") as f:
///     der = f.read()
/// pem = synta.der_to_pem(der, "CERTIFICATE")
/// ```
#[pyfunction]
fn der_to_pem<'py>(py: Python<'py>, der: &[u8], label: &str) -> Bound<'py, pyo3::types::PyBytes> {
    pyo3::types::PyBytes::new(py, &synta_certificate::der_to_pem(label, der))
}

/// Decode PEM blocks to DER bytes.
///
/// Strips ``-----BEGIN ...-----`` / ``-----END ...-----`` boundary lines and
/// decodes the base64 body of every PEM block found in the input.  Implemented
/// in pure Rust — no external dependencies required.
///
/// Always returns :class:`list` [:class:`bytes`] — one entry per PEM block.
/// Raises :exc:`ValueError` if no PEM block is found.
///
/// ```python,ignore
/// # Single block — index into the list:
/// der = synta.pem_to_der(open("cert.pem", "rb").read())[0]
/// cert = synta.Certificate.from_der(der)
///
/// # Bundle / chain:
/// ders = synta.pem_to_der(open("bundle.pem", "rb").read())
/// certs = [synta.Certificate.from_der(d) for d in ders]
/// ```
#[pyfunction]
fn pem_to_der<'py>(
    py: Python<'py>,
    data: &[u8],
) -> PyResult<pyo3::Bound<'py, pyo3::types::PyList>> {
    let blocks = synta_certificate::pem_blocks(data);
    if blocks.is_empty() {
        return Err(pyo3::exceptions::PyValueError::new_err(
            "no PEM block found in input",
        ));
    }
    let list = pyo3::types::PyList::empty(py);
    for (_, block) in &blocks {
        list.append(pyo3::types::PyBytes::new(py, block))?;
    }
    Ok(list)
}

/// Compute a hash digest of arbitrary bytes.
///
/// Returns a :class:`bytes` object containing the raw (binary) digest.
/// ``algorithm`` must be one of ``"sha1"``, ``"sha224"``, ``"sha256"``,
/// ``"sha384"``, ``"sha512"``, or ``"md5"``.  Raises :exc:`ValueError` for
/// unknown algorithm names or crypto backend errors.
///
/// ```python,ignore
/// import synta
///
/// # Hash a certificate DER blob:
/// digest_bytes = synta.digest("sha256", cert_der)
/// print(digest_bytes.hex())
///
/// # Hash an arbitrary byte string:
/// digest_bytes = synta.digest("sha1", b"hello world")
/// ```
#[pyfunction]
fn digest<'py>(
    py: Python<'py>,
    algorithm: &str,
    data: &[u8],
) -> PyResult<pyo3::Bound<'py, pyo3::types::PyBytes>> {
    use synta_certificate::{default_data_hasher, DataHasher};
    let d = default_data_hasher()
        .hash_data(algorithm, data)
        .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
    Ok(pyo3::types::PyBytes::new(py, &d))
}

/// Format a DER-encoded X.500 Name as an RFC 4514 distinguished name string.
///
/// ``name_der`` must be the complete TLV bytes of the Name SEQUENCE (tag +
/// length + value), as returned by :attr:`Certificate.issuer_raw_der` or
/// :attr:`Certificate.subject_raw_der`.
///
/// Returns a string like ``"CN=example.com, O=Example Inc, C=US"``.
/// Returns an empty string if ``name_der`` cannot be parsed.
///
/// ```python,ignore
/// dn = synta.format_dn(cert.subject_raw_der)
/// print(dn)  # CN=example.com, O=Example Inc, C=US
/// ```
#[pyfunction]
fn format_dn(name_der: &[u8]) -> String {
    synta_certificate::name::format_dn(name_der)
}

/// Format a DER-encoded X.500 Name in OpenSSL slash-separated form.
///
/// ``name_der`` must be the complete TLV bytes of the Name SEQUENCE (tag +
/// length + value), as returned by :attr:`Certificate.issuer_raw_der` or
/// :attr:`Certificate.subject_raw_der`.
///
/// Returns a string like ``"/C=US/O=Example Inc/CN=example.com"``.
/// Returns an empty string if ``name_der`` cannot be parsed.
///
/// ```python,ignore
/// dn = synta.format_dn_slash(cert.subject_raw_der)
/// print(dn)  # /C=US/O=Example Inc/CN=example.com
/// ```
#[pyfunction]
fn format_dn_slash(name_der: &[u8]) -> String {
    synta_certificate::name::format_dn_slash(name_der)
}

/// Find the value bytes of an X.509v3 extension by OID.
///
/// ``ext_seq_der`` must be the complete DER bytes of the ``Extensions``
/// SEQUENCE (i.e. the bytes captured by the ``extensions`` field of a
/// parsed ``Certificate`` after the ``[3] EXPLICIT`` wrapper is stripped).
/// Use :meth:`Certificate.get_extension_value_der` for the more common
/// case of looking up an extension value in a certificate directly.
///
/// ``oid`` is either a dotted-decimal OID string (e.g. ``"2.5.29.17"``)
/// or an :class:`ObjectIdentifier` instance.
///
/// Returns the extension value bytes (the content of the ``extnValue``
/// OCTET STRING, without the OCTET STRING TLV wrapper), or ``None`` if
/// no matching extension is present.  Raises :exc:`ValueError` if ``oid``
/// is not a valid OID.
///
/// ```python,ignore
/// ext_der = cert.get_extension_value_der("2.5.29.17")
/// ```
#[pyfunction]
fn find_extension_value<'py>(
    py: Python<'py>,
    ext_seq_der: &[u8],
    oid: &Bound<'_, PyAny>,
) -> PyResult<Py<PyAny>> {
    use std::str::FromStr;
    use synta::ObjectIdentifier;

    let oid_val: ObjectIdentifier =
        if let Ok(oid_ref) = oid.extract::<pyo3::PyRef<crate::types::PyObjectIdentifier>>() {
            oid_ref.inner.clone()
        } else if let Ok(s) = oid.extract::<String>() {
            ObjectIdentifier::from_str(&s)
                .map_err(|_| pyo3::exceptions::PyValueError::new_err(format!("invalid OID: {s}")))?
        } else {
            return Err(pyo3::exceptions::PyTypeError::new_err(
                "oid must be a str or ObjectIdentifier",
            ));
        };

    match synta_certificate::find_extension_value(ext_seq_der, oid_val.components()) {
        Some(bytes) => Ok(pyo3::types::PyBytes::new(py, bytes).into_any().unbind()),
        None => Ok(py.None()),
    }
}

/// Encode a list of ``(tag_number, value_bytes)`` pairs as a DER ``SEQUENCE OF GeneralName``.
///
/// ``entries`` must be a list of ``(tag_number: int, value: bytes)`` tuples in
/// the same format returned by :func:`parse_general_names`.  Tag numbers follow
/// RFC 5280 (see :mod:`synta.general_name` for named constants).
///
/// Returns the DER-encoded ``SEQUENCE OF GeneralName`` bytes on success, or
/// ``None`` if any entry cannot be encoded.  Raises :exc:`ValueError` if the
/// input is structurally invalid (e.g. not a list of 2-tuples).
///
/// ```python,ignore
/// import synta
/// import synta.general_name as gn
///
/// san_der = synta.encode_general_names([
///     (gn.DNS_NAME, b"example.com"),
///     (gn.IP_ADDRESS, b"\\xc0\\xa8\\x00\\x01"),  # 192.168.0.1
/// ])
/// ```
#[pyfunction]
fn encode_general_names<'py>(
    py: Python<'py>,
    entries: &Bound<'_, pyo3::types::PyList>,
) -> PyResult<Py<PyAny>> {
    let mut rust_entries: Vec<(u32, Vec<u8>)> = Vec::with_capacity(entries.len());
    for item in entries.iter() {
        let tuple = item.cast::<pyo3::types::PyTuple>().map_err(|_| {
            pyo3::exceptions::PyValueError::new_err("each entry must be a (int, bytes) tuple")
        })?;
        if tuple.len() != 2 {
            return Err(pyo3::exceptions::PyValueError::new_err(
                "each entry must be a 2-tuple (tag_number, bytes)",
            ));
        }
        let tag_num: u32 = tuple
            .get_item(0)?
            .extract()
            .map_err(|_| pyo3::exceptions::PyValueError::new_err("tag_number must be an int"))?;
        let value: Vec<u8> = tuple
            .get_item(1)?
            .extract()
            .map_err(|_| pyo3::exceptions::PyValueError::new_err("value must be bytes"))?;
        rust_entries.push((tag_num, value));
    }

    let refs: Vec<(u32, &[u8])> = rust_entries
        .iter()
        .map(|(t, v)| (*t, v.as_slice()))
        .collect();

    match synta_certificate::encode_general_names(&refs) {
        Some(encoded) => Ok(pyo3::types::PyBytes::new(py, &encoded).into_any().unbind()),
        None => Ok(py.None()),
    }
}

/// Build the DER encoding of an ``AlgorithmIdentifier`` for signing.
///
/// ``key_oid`` is the public key algorithm OID — either a dotted-decimal
/// string (e.g. ``"1.2.840.113549.1.1.1"`` for RSA) or an
/// :class:`ObjectIdentifier` instance.
///
/// ``hash_algo`` is the hash algorithm name, e.g. ``"sha256"``, ``"sha384"``,
/// or ``"sha512"``.
///
/// Returns the DER bytes of the ``AlgorithmIdentifier`` SEQUENCE, or ``None``
/// if the key OID is not recognised or the hash algorithm is not valid for
/// the key type.  Raises :exc:`ValueError` if ``key_oid`` is not a valid OID.
///
/// ```python,ignore
/// alg_der = synta.signing_algorithm_der("1.2.840.113549.1.1.1", "sha256")
/// # → DER for sha256WithRSAEncryption AlgorithmIdentifier
/// ```
#[pyfunction]
fn signing_algorithm_der<'py>(
    py: Python<'py>,
    key_oid: &Bound<'_, PyAny>,
    hash_algo: &str,
) -> PyResult<Py<PyAny>> {
    use std::str::FromStr;
    use synta::ObjectIdentifier;

    let oid_val: ObjectIdentifier =
        if let Ok(oid_ref) = key_oid.extract::<pyo3::PyRef<crate::types::PyObjectIdentifier>>() {
            oid_ref.inner.clone()
        } else if let Ok(s) = key_oid.extract::<String>() {
            ObjectIdentifier::from_str(&s)
                .map_err(|_| pyo3::exceptions::PyValueError::new_err(format!("invalid OID: {s}")))?
        } else {
            return Err(pyo3::exceptions::PyTypeError::new_err(
                "key_oid must be a str or ObjectIdentifier",
            ));
        };

    match synta_certificate::signing_algorithm_der(&oid_val, hash_algo) {
        Some(der) => Ok(pyo3::types::PyBytes::new(py, &der).into_any().unbind()),
        None => Ok(py.None()),
    }
}

/// Test whether a bit position is set in a KeyUsage BIT STRING value.
///
/// ``ku_value_bytes`` must be the raw value bytes of the KeyUsage BIT STRING
/// (i.e. the bytes inside the OCTET STRING wrapper of the extension value,
/// after decoding the BIT STRING tag and length — the first byte is the
/// unused-bits count, followed by the named-bit flags).
///
/// ``bit_n`` is the named-bit index as defined in RFC 5280 §4.2.1.3.
/// Named-bit constants are available in :mod:`synta.cert` (e.g.
/// ``synta.cert.KEY_USAGE_DIGITAL_SIGNATURE == 0``).
///
/// Returns ``True`` if bit ``bit_n`` is set, ``False`` otherwise.
///
/// ```python,ignore
/// ku_der = cert.get_extension_value_der("2.5.29.15")
/// # bit 5 = keyCertSign
/// is_ca = synta.key_usage_bit(ku_der, 5)
/// ```
#[pyfunction]
fn key_usage_bit(ku_value_bytes: &[u8], bit_n: usize) -> PyResult<bool> {
    let mut dec = synta::Decoder::new(ku_value_bytes, synta::Encoding::Der);
    let ku: synta_certificate::KeyUsage = dec.decode().map_err(|e| {
        pyo3::exceptions::PyValueError::new_err(format!("invalid KeyUsage DER: {e}"))
    })?;
    Ok(synta_certificate::key_usage_bit(&ku, bit_n))
}

/// Decode a DER-encoded ``SubjectPublicKeyInfo`` into a dictionary.
///
/// ``spki_der`` must be the complete DER bytes of the
/// ``SubjectPublicKeyInfo`` SEQUENCE TLV, as returned by
/// :attr:`Certificate.subject_public_key_info_der` or
/// :meth:`PublicKey.to_der`.
///
/// Returns a :class:`dict` with at minimum these keys:
///
/// * ``"algorithm_oid"`` (:class:`str`) — dotted OID of the public-key algorithm
/// * ``"key_bytes"`` (:class:`bytes`) — raw key bytes from the BIT STRING
///
/// For RSA keys the dict additionally contains:
///
/// * ``"modulus"`` (:class:`bytes`) — raw modulus bytes (may include 0x00 sign byte)
/// * ``"exponent"`` (:class:`int`) — public exponent (typically 65537)
/// * ``"bit_count"`` (:class:`int`) — key size in bits
///
/// For EC keys the dict additionally contains:
///
/// * ``"bit_count"`` (:class:`int`) — key size in bits
/// * ``"curve_oid"`` (:class:`str`) — dotted OID of the named curve
/// * ``"curve_short_name"`` (:class:`str` or ``None``) — short name, e.g. ``"prime256v1"``
/// * ``"curve_nist_name"`` (:class:`str` or ``None``) — NIST name, e.g. ``"P-256"``
///
/// Raises :exc:`ValueError` if ``spki_der`` cannot be parsed.
///
/// ```python,ignore
/// spki_der = cert.subject_public_key_info_der
/// info = synta.decode_public_key_info(spki_der)
/// print(info["algorithm_oid"])   # e.g. "1.2.840.10045.2.1" for EC
/// print(info.get("curve_nist_name"))  # "P-256"
/// ```
#[pyfunction]
fn decode_public_key_info<'py>(
    py: Python<'py>,
    spki_der: &[u8],
) -> PyResult<Bound<'py, pyo3::types::PyDict>> {
    use pyo3::types::{PyBytes, PyDict};
    use synta::{Decoder, Encoding};
    use synta_certificate::SubjectPublicKeyInfo;

    let mut dec = Decoder::new(spki_der, Encoding::Der);
    let spki: SubjectPublicKeyInfo<'_> = dec
        .decode()
        .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("invalid SPKI DER: {e}")))?;

    let alg_oid = spki
        .algorithm
        .algorithm
        .components()
        .iter()
        .map(|n| n.to_string())
        .collect::<Vec<_>>()
        .join(".");
    let key_bytes = spki.subject_public_key.as_bytes();
    let key_bit_len = spki.subject_public_key.bit_len();

    let info = synta_certificate::decode_public_key_info(
        &spki.algorithm.algorithm,
        spki.algorithm.parameters.as_ref(),
        key_bytes,
        key_bit_len,
    );

    let dict = PyDict::new(py);
    dict.set_item("algorithm_oid", &alg_oid)?;

    match info {
        synta_certificate::PublicKeyInfo::Rsa {
            modulus,
            exponent,
            bit_count,
        } => {
            dict.set_item("key_bytes", PyBytes::new(py, &modulus))?;
            dict.set_item("modulus", PyBytes::new(py, &modulus))?;
            dict.set_item("exponent", exponent)?;
            dict.set_item("bit_count", bit_count)?;
        }
        synta_certificate::PublicKeyInfo::Ec {
            key_bytes,
            bit_count,
            curve_short_name,
            curve_nist_name,
            curve_oid_str,
        } => {
            dict.set_item("key_bytes", PyBytes::new(py, &key_bytes))?;
            dict.set_item("bit_count", bit_count)?;
            dict.set_item("curve_oid", &curve_oid_str)?;
            match curve_short_name {
                Some(name) => dict.set_item("curve_short_name", name)?,
                None => dict.set_item("curve_short_name", py.None())?,
            }
            match curve_nist_name {
                Some(name) => dict.set_item("curve_nist_name", name)?,
                None => dict.set_item("curve_nist_name", py.None())?,
            }
        }
        synta_certificate::PublicKeyInfo::Unknown {
            key_bytes,
            bit_count,
            ..
        } => {
            dict.set_item("key_bytes", PyBytes::new(py, &key_bytes))?;
            dict.set_item("bit_count", bit_count)?;
        }
    }

    Ok(dict)
}