Example Programs
Twenty-eight runnable programs in examples/ exercise every binding documented
in this guide. Each program is self-contained and runs with:
uv run python3 examples/example_<name>.py
from the repository root (after maturin develop).
1. example_pem_helpers.py — PEM/DER conversion
Bindings: pem_to_der, der_to_pem, Certificate.from_pem, Certificate.to_pem,
CertificationRequest.from_pem, CertificationRequest.to_pem,
CertificateList.from_pem, CertificateList.to_pem.
- Round-trip a single PEM certificate block through
pem_to_der/der_to_pem(pem_to_deralways returnslist[bytes]). - Show
pem_to_derwith a multi-block PEM chain. - Use
Certificate.from_pemon a single block and on a two-certificate chain. - Use
Certificate.to_pemon a single cert and a list of certs.
2. example_certificate_fields.py — All Certificate properties
Bindings: Certificate.from_der, Certificate.full_from_der, all Certificate
properties (serial_number, version, issuer, issuer_raw_der, subject,
subject_raw_der, not_before, not_after, signature_algorithm,
signature_algorithm_oid, signature_algorithm_params, signature_value,
public_key_algorithm, public_key_algorithm_oid, public_key_algorithm_params,
public_key, tbs_bytes), and Certificate.to_der() method.
- Parse the same certificate with
from_der(lazy) andfull_from_der(eager). - Print every property with its Python type.
- Verify
to_der()round-trip (re-parse the returned bytes). - Show
signature_algorithm_paramsisNonefor Ed25519 and non-Nonefor RSA.
3. example_certificate_extensions.py — Extension access and SAN parsing
Bindings: Certificate.subject_alt_names, Certificate.extensions_der,
Certificate.get_extension_value_der, synta.general_name tag constants,
synta.parse_general_names, synta.parse_name_attrs,
synta.oids.SUBJECT_ALT_NAME, synta.oids.BASIC_CONSTRAINTS,
synta.oids.SUBJECT_KEY_IDENTIFIER, Decoder.decode_sequence, Decoder.peek_tag,
Decoder.decode_implicit_tag, Decoder.decode_explicit_tag,
Decoder.remaining_bytes, Decoder.decode_raw_tlv, Decoder.is_empty.
- Call
cert.subject_alt_names()for high-level SAN access; dispatch onsynta.general_nameconstants (gn.DNS_NAME,gn.IP_ADDRESS, etc.); useipaddress.ip_address(content)for IP rendering. - Verify that a certificate without a SAN extension returns an empty list.
- Access
extensions_derand iterate the raw extension TLVs. - Look up individual extensions by
get_extension_value_der. - Parse SAN entries manually with
peek_tag/decode_implicit_tagas a lower-level alternative tosubject_alt_names(). - Demonstrate
peek_tagfor CHOICE dispatch;remaining_bytesfor primitive implicit values. - Look up BasicConstraints and decode the cA BOOLEAN.
4. example_certificate_pyca.py — PyCA interoperability
Bindings: Certificate.to_pyca, Certificate.from_pyca.
- Parse a DER certificate with synta, then call
.to_pyca()for cryptographic operations. - Load a PyCA certificate, convert to synta with
from_pyca(), and compare fields. - Show
ImportErrormessage whencryptographyis absent (caught and printed).
5. example_csr.py — PKCS#10 CSR parsing
Bindings: CertificationRequest.from_der, CertificationRequest.from_pem,
CertificationRequest.to_pem, and all CertificationRequest properties.
- Parse a CSR from DER and print every field.
- Round-trip through PEM with
from_pem/to_pem. - Verify
subject_raw_derby re-decoding it as a raw Name SEQUENCE.
6. example_crl.py — CRL parsing
Bindings: CertificateList.from_der, CertificateList.from_pem,
CertificateList.to_pem, and all CertificateList properties.
- Parse a CRL and print issuer, dates, algorithm, revoked count.
- Show
next_updateisNonefor CRLs that omit the field. - Round-trip through
to_pem/from_pem.
7. example_ocsp.py — OCSP response parsing
Bindings: OCSPResponse.from_der, OCSPResponse.from_pem, OCSPResponse.to_pem,
and all OCSPResponse properties.
- Parse a successful OCSP response; print
status,response_type_oid, length ofresponse_bytes. - Parse a non-successful response (e.g.
tryLater); confirmresponse_bytesisNone. - Round-trip through
to_pem/from_pem.
8. example_pkcs7.py — PKCS#7 certificate bundles
Bindings: load_der_pkcs7_certificates, load_pem_pkcs7_certificates.
- Load a
.p7bfile and print the subject of each extracted certificate. - Demonstrate PEM-encoded PKCS#7 with
load_pem_pkcs7_certificates. - Show
ValueErrorfor non-PKCS#7 input.
9. example_pkcs12.py — PKCS#12 archive parsing and creation
Bindings: load_pkcs12_certificates, load_pkcs12_keys, load_pkcs12,
create_pkcs12.
- Parse a password-less PKCS#12 file; print subjects of extracted certificates.
- Extract private keys using
load_pkcs12_keys; show raw PKCS#8 DER length. - Extract both with
load_pkcs12; show the(certs, keys)tuple. - Parse an AES-256-CBC encrypted PKCS#12 with a password.
- Show
ValueErrorfor wrong password (encrypted case, withopensslfeature). - Build a PFX from extracted certificates using
create_pkcs12without a password. - Build a password-protected PFX with
create_pkcs12(requiresopensslfeature). - Build a cert+key PFX bundle.
- Roundtrip: build an archive then parse it back and verify the extracted certificates.
10. example_pki_blocks.py — Format-agnostic PKI reader
Bindings: read_pki_blocks.
- Pass PEM, DER, PKCS#7, and PKCS#12 bytes to
read_pki_blocksand print the(label, len(der))tuples returned. - Show PKCS#12 password handling.
11. example_objectidentifier.py — ObjectIdentifier constructors and operations
Bindings: ObjectIdentifier(str), ObjectIdentifier.from_components,
ObjectIdentifier.from_der_value, ObjectIdentifier.components,
ObjectIdentifier.__eq__, ObjectIdentifier.__hash__,
Decoder.decode_oid, Encoder.encode_oid, Encoder.encode_oid_object.
- Construct OIDs via all three constructors; verify they compare equal.
- Show
__eq__working against a dotted string. - Use OIDs as dict keys (demonstrate hashability).
- Round-trip through
encode_oid/decode_oid. - Show
from_der_valuewith the raw content bytes from an implicit-tag context.
12. example_oids_catalog.py — synta.oids constant groups
Bindings: every constant in synta.oids and synta.oids.attr,
plus the helper functions identify_signature_algorithm,
identify_public_key_algorithm.
- Print algorithm OIDs (RSA, EC, EdDSA, ML-DSA, ML-KEM).
- Print hash OIDs (SHA-2, SHA-3).
- Print SLH-DSA OIDs.
- Print prefix OIDs and demonstrate
components()-based prefix matching. - Print X.509v3 extension OIDs.
- Print EKU OIDs.
- Print PKINIT OIDs.
- Print MS PKI OIDs.
- Print all nine PKCS#9 attribute OIDs (
PKCS9_EMAIL_ADDRESS,PKCS9_CONTENT_TYPE,PKCS9_MESSAGE_DIGEST,PKCS9_SIGNING_TIME,PKCS9_COUNTERSIGNATURE,PKCS9_CHALLENGE_PASSWORD,PKCS9_EXTENSION_REQUEST,PKCS9_FRIENDLY_NAME,PKCS9_LOCAL_KEY_ID). - Print every
synta.oids.attrDN attribute OID with its RFC 4514 label.
13. example_time_types.py — UtcTime and GeneralizedTime
Bindings: UtcTime(…), UtcTime properties (year, month, day, hour,
minute, second), GeneralizedTime(…), GeneralizedTime properties,
Encoder.encode_utc_time, Encoder.encode_utc_time_object,
Encoder.encode_generalized_time, Encoder.encode_generalized_time_object,
Decoder.decode_utc_time, Decoder.decode_generalized_time.
- Construct both time types and inspect every property.
- Round-trip each through encode / decode; verify string representations.
- Show millisecond sub-second precision on
GeneralizedTime. - Show
ValueErrorfor out-of-range UTCTime year (< 1950 or > 2049). - Demonstrate
encode_utc_time_objectandencode_generalized_time_objectvariants.
14. example_integer_advanced.py — Integer edge cases and bigint
Bindings: Integer(int), Integer.from_bytes, Integer.from_u64,
Integer.to_int, Integer.to_i128, Integer.to_bytes,
Encoder.encode_integer (bigint path), Encoder.encode_integer_object.
- Construct integers via all three constructors.
- Show
to_int()succeeds for small values; raisesOverflowErrorfor 20-byte serials. - Use
to_i128()for up to 16-byte values (i128 max = 2¹²⁷−1); showOverflowErrorbeyond that. - Use
to_bytes()for arbitrary-precision big-endian representation. - Encode a 20-byte certificate serial number via
encode_integer(large_python_int). - Verify
encode_integer_objectround-trip.
15. example_string_types_advanced.py — Alternative string constructors
Bindings: TeletexString.from_latin1, TeletexString.from_str,
GeneralString.from_ascii, GeneralString.from_str,
UniversalString.from_bytes, BmpString.from_bytes,
plus to_bytes() / as_str() on each.
- Construct
TeletexStringfrom bytes and Latin-1 strings;GeneralStringfrom bytes and ASCII strings. - Construct
UniversalStringandBmpStringfrom raw UCS-4/UCS-2 byte buffers. - Show
ValueErrorwhen non-BMP code points are passed toBmpString. - Round-trip each through the encoder / decoder.
16. example_decoder_advanced.py — Advanced Decoder operations
Bindings: Decoder.decode_set, Decoder.peek_tag, Decoder.decode_raw_tlv,
Decoder.remaining_bytes, Decoder.decode_implicit_tag, Decoder.position,
Decoder.remaining, Decoder.is_empty, Decoder.decode_any_str.
- Build a hand-crafted SET and decode it with
decode_set. - Use
peek_tagin a loop to drive CHOICE dispatch. - Capture unknown elements with
decode_raw_tlv. - Use
decode_implicit_tag+remaining_bytesto decode a primitive implicit type (e.g.[2] IMPLICIT IA5Stringfor a dNSName GeneralName). - Show
position()andremaining()advancing through multi-element input. - Use
decode_any_str()to decode a mixed-string SEQUENCE without tag inspection.
17. example_encoder_advanced.py — Advanced Encoder operations
Bindings: Encoder.encode_implicit_tag, Encoder.encode_set,
Encoder.encode_explicit_tag, Encoder.encode_sequence,
and all _object variants not demonstrated elsewhere.
- Build a SET containing two PrintableStrings using
encode_set. - Encode an implicit context tag
[2] IMPLICIT IA5String(dNSName). - Encode a nested structure: SEQUENCE { [0] EXPLICIT SEQUENCE { INTEGER } }.
- Demonstrate every
_objectencode variant with a typed object sourced from a decode. - Show
ValueErrorfor unknown tag class strings.
18. example_krb5_principal.py — Kerberos principal names
Bindings: synta.krb5.Krb5PrincipalName, synta.krb5.KRB5_PRINCIPAL_NAME_OID,
and every NT_* constant.
- Construct
Krb5PrincipalNameinstances for each name type (NT_PRINCIPAL,NT_SRV_INST,NT_SRV_HST,NT_ENTERPRISE,NT_WELLKNOWN). - Encode each with
to_der()and decode back withfrom_der(). - Verify realm, name_type, and components survive the round-trip.
- Show
__eq__and__repr__. - Print
KRB5_PRINCIPAL_NAME_OIDand demonstrate it matchessynta.oids.ID_PKINIT_SAN. - Show
ValueErrorfor non-ASCII realm or component.
19. example_krb5_pkinit.py — PKINIT protocol classes
Bindings: EncryptionKey, Checksum, KDFAlgorithmId, IssuerAndSerialNumber,
ExternalPrincipalIdentifier, PKAuthenticator, AuthPack, PaPkAsReq,
DHRepInfo, KDCDHKeyInfo, ReplyKeyPack, PaPkAsRep.
For each class: parse hand-crafted DER bytes with from_der, access every property,
and print a summary of key values.
20. example_error_handling.py — Exception catalogue
Bindings: synta.SyntaError, ValueError, OverflowError, EOFError.
- Inspect
SyntaErroras a module exception class (MRO,issubclasscheck). - Demonstrate
EOFErrorfrom empty input, tag-only input, and truncated value inDecoder. - Demonstrate
ValueErrorfrom tag mismatch (decoding BOOLEAN as INTEGER). - Demonstrate
ValueErrorfrom DER constraint violations (non-canonical BOOLEAN, non-minimal INTEGER). - Demonstrate
OverflowErrorfromInteger.to_int()andto_i128()on values exceeding the target type. - Demonstrate
ValueErrorfrom constructor validation:BmpStringwith a non-BMP character,GeneralizedTimewith an invalid month,ObjectIdentifierwith a malformed string,Krb5PrincipalNamewith a non-ASCII realm,GeneralString.from_asciiwith a non-ASCII character.
21. example_cms_encrypted_data.py — CMS EncryptedData round-trip
Bindings: synta.cms.EncryptedData, synta.cms.ID_AES128_CBC,
synta.cms.ID_AES192_CBC, synta.cms.ID_AES256_CBC.
Requires the openssl Cargo feature (maturin develop --features openssl).
- Create an
EncryptedDatawithEncryptedData.create(AES-128-CBC) and inspect all properties:version,content_type,content_encryption_algorithm_oid,content_encryption_algorithm_params(IV extraction),encrypted_content. - Decrypt → replace text in plaintext → re-encrypt with a fresh random IV;
verify the round-trip with
to_der()/from_der(). - Encrypt with each of AES-128/192/256-CBC using
ID_AES128_CBC,ID_AES192_CBC,ID_AES256_CBC; confirm random IV differs across calls. - Verify synta-produced ciphertext with
openssl enc -d(synta → openssl interop). - Inspect the
EncryptedDataDER structure withopenssl asn1parse. - Encrypt raw bytes with
openssl enc -e, wrap in anEncryptedDataDER by hand, parse withfrom_der, and decrypt with synta (openssl → synta interop).
22. example_x509_verify.py — X.509 certificate chain verification
Bindings: synta.x509.TrustStore, synta.x509.VerificationPolicy,
synta.x509.verify_server_certificate, synta.x509.verify_client_certificate,
synta.x509.X509VerificationError.
Requires the openssl Cargo feature (maturin develop --features openssl).
- Build a self-signed root CA DER in memory with
openssl req -x509and load it into aTrustStore; printstore.lenandrepr(store). - Verify a leaf certificate signed by that root with
verify_server_certificate; print the chain length and each certificate’s subject withsynta.Certificate.from_der. - Demonstrate
VerificationPolicyvariants: single name, multi-nameany, multi-nameall, fixedvalidation_time,max_chain_depth,profile="rfc5280". - Demonstrate client certificate verification with
verify_client_certificate. - Show that
X509VerificationErroris raised when the trust store does not contain the issuer, the server name does not match the SAN, and the validation time is outside the validity window.
23. example_general_name.py — Typed GeneralName API
Bindings: synta.general_name.DNSName, synta.general_name.IPAddress,
synta.general_name.RFC822Name, synta.general_name.OtherName,
synta.general_name.UniformResourceIdentifier, synta.parse_general_names.
- Call
cert.subject_alt_names()on a certificate with four SANs (twodNSName, oneiPAddress, onerfc822Name); dispatch byisinstance. - Use
cert.general_names(oid)to retrieve SANs by extension OID. - Use
synta.parse_general_names(san_der)for low-level tag/bytes access. - Demonstrate integer tag constants (
gn.DNS_NAME,gn.IP_ADDRESS, etc.).
24. example_pkixalgs.py — RFC 3279 algorithm parameter types
Bindings: synta.pkixalgs.DssParms, synta.pkixalgs.ECParameters,
synta.pkixalgs.EcdsaSigValue, synta.pkixalgs.DssSigValue and OID constants.
- Parse
DssParms(DSA domain parameters P/Q/G) from hand-crafted DER; verify round-trip. - Parse
ECParametersinnamedCurveform; accessarmandnamed_curve_oid. - Parse
EcdsaSigValue(r and s components of an ECDSA signature). - Use OID constants:
ID_DSA,ID_EC_PUBLIC_KEY,ECDSA_WITH_SHA256,PRIME256V1.
25. example_ac.py — RFC 5755 Attribute Certificates
Bindings: synta.ac.AttributeCertificate and related OID constants.
- Build a minimal RFC 5755 v2 Attribute Certificate from scratch in DER.
- Access all eight
AttributeCertificateproperties:version,holder,issuer,signature_algorithm,serial_number,not_before,not_after,attributes. - Demonstrate OID constants:
ID_AT_ROLE,ID_PE_AC_AUDIT_IDENTITY,ID_CE_SUBJECT_DIRECTORY_ATTRIBUTES.
26. example_ms_pki.py — Microsoft PKI (AD CS) extension types
Bindings: synta.ms_pki.MSCSTemplateV2, synta.ms_pki.RequestClientInfo
and OID constants.
- Parse
MSCSTemplateV2with major version only and with both versions; verifytemplate_id,template_major_version,template_minor_version, andto_der()round-trip. - Parse
RequestClientInfowith all four fields present, with partial fields, and from an empty SEQUENCE. - Print all nineteen OID constants with their dot-notation values.
27. example_spnego.py — SPNEGO negotiation tokens (RFC 4178)
Bindings: synta.spnego.NegTokenInit, synta.spnego.NegTokenResp,
synta.spnego.NegotiationToken, NEG_STATE_* constants, SPNEGO_OID.
DER encoding note: GssapiSpnego.asn1 uses
DEFINITIONS IMPLICIT TAGS. The example builds all test vectors using IMPLICIT encoding helpers.
- Parse
NegTokenInitwithmech_types(two OIDs) andmech_token; verify each property and confirmreq_flags/mech_list_micare absent. - Parse an empty
NegTokenInitSEQUENCE; verifymech_types == []. - Parse
NegotiationTokenin thenegTokenInitCHOICE arm (0xa0) and thenegTokenResparm (0xa1). - Parse a GSSAPI-wrapped token (
0x60APPLICATION tag) and verify thatfrom_derstrips the OID prefix automatically. - Parse
NegTokenRespwithneg_state3 (NEG_STATE_REQUEST_MIC) and aresponse_token; verifysupported_mechandmech_list_mic. - Verify all four
NEG_STATE_*integer constants andSPNEGO_OID.
28. example_mtc.py — Merkle Tree Certificates
Bindings: synta.mtc.ProofNode, synta.mtc.Subtree, synta.mtc.SubtreeProof,
synta.mtc.InclusionProof, synta.mtc.LogID, synta.mtc.CosignerID,
synta.mtc.Checkpoint, synta.mtc.SubtreeSignature,
synta.mtc.MerkleTreeCertEntry, synta.mtc.LandmarkID.
- Parse
ProofNode(left and right variants); verifyis_leftandhash. - Parse
Subtree; verifystart,end, andvalue. - Parse
SubtreeProofwith both subtree lists; verify element count. - Parse
InclusionProof; verifylog_entry_index,tree_size, and path length. - Parse
LogIDandCosignerID; verifyhash_alg_oidandpublic_key_der. - Parse
Checkpoint; verify all five properties. - Parse
SubtreeSignature; verifycosigner_id,tree_size,root_hash. - Parse
MerkleTreeCertEntryas aLandmarkCertificateCHOICE arm; verifylandmark_idwithtree_size. - Verify
repr()output forLandmarkID.