Fast ASN.1 parser and serializer with definitions for private keys, public keys, certificates, CRL, OCSP, CMS, PKCS#3, PKCS#7, PKCS#8, PKCS#12, PKCS#5, X.509 and TSP
npx @tessl/cli install tessl/pypi-asn1crypto@1.5.0A fast, pure Python library for parsing and serializing ASN.1 structures with comprehensive support for cryptographic standards. ASN1Crypto provides a pythonic API for handling X.509 certificates, private keys, CRLs, OCSP, CMS, PKCS standards, and other cryptographic ASN.1 structures without requiring any C extensions.
pip install asn1cryptoimport asn1cryptoFor specific functionality:
from asn1crypto import core, x509, keys, cms, pemCommon pattern for loading encoded data:
from asn1crypto.x509 import Certificate
from asn1crypto.keys import PrivateKeyInfoimport asn1crypto.x509
import asn1crypto.keys
import asn1crypto.pem
# Load a PEM-encoded certificate
with open('cert.pem', 'rb') as f:
cert_pem = f.read()
# Convert PEM to DER
if asn1crypto.pem.detect(cert_pem):
_, _, cert_der = asn1crypto.pem.unarmor(cert_pem)
else:
cert_der = cert_pem
# Parse the certificate
cert = asn1crypto.x509.Certificate.load(cert_der)
# Access certificate information
print(f"Subject: {cert.subject.human_friendly}")
print(f"Issuer: {cert.issuer.human_friendly}")
print(f"Serial Number: {cert.serial_number}")
print(f"Valid From: {cert.not_valid_before}")
print(f"Valid Until: {cert.not_valid_after}")
# Load and parse a private key
with open('key.pem', 'rb') as f:
key_pem = f.read()
_, _, key_der = asn1crypto.pem.unarmor(key_pem)
private_key = asn1crypto.keys.PrivateKeyInfo.load(key_der)
print(f"Key Algorithm: {private_key.algorithm}")
print(f"Key Size: {private_key.bit_size}")ASN1Crypto follows a layered architecture built around the ASN.1 standard:
Sequence, OctetString, Integer, etc.) providing the foundation for all ASN.1 structuresThis design enables efficient parsing through lazy loading, delayed parsing, and preservation of original encoded data for performance optimization, especially with large cryptographic structures.
Universal ASN.1 data types and low-level parsing functionality. Includes primitive types (Boolean, Integer, OctetString), container types (Sequence, Set, Choice), string types, and time types. Provides the foundation for all higher-level cryptographic structures.
class Asn1Value:
@classmethod
def load(cls, encoded_data, strict=False): ...
def dump(self, force=False): ...
@property
def native(self): ...
def load(encoded_data, strict=False): ...Algorithm identifier structures and parameters for cryptographic operations. Covers digest algorithms (MD5, SHA family), signature algorithms (RSA, DSA, ECDSA), encryption algorithms, key derivation functions, and MAC algorithms with their associated parameters.
class AlgorithmIdentifier(core.Sequence): ...
class DigestAlgorithm(core.Choice): ...
class SignedDigestAlgorithm(core.Choice): ...
class EncryptionAlgorithm(core.Choice): ...Public and private key structures for RSA, DSA, and elliptic curve algorithms, along with comprehensive X.509 certificate support. Includes certificate parsing, validation helpers, distinguished names, and extensive certificate extension support.
class Certificate(core.Sequence): ...
class PublicKeyInfo(core.Sequence): ...
class PrivateKeyInfo(core.Sequence): ...
class Name(core.Sequence): ...Certificate revocation lists (CRLs), Online Certificate Status Protocol (OCSP) structures, and Certificate Signing Requests (CSRs). Essential components for PKI certificate lifecycle management and validation.
class CertificateList(core.Sequence): ...
class OCSPRequest(core.Sequence): ...
class OCSPResponse(core.Sequence): ...
class CertificationRequest(core.Sequence): ...High-level cryptographic message formats including CMS/PKCS#7 (signed data, enveloped data, etc.), PKCS#12 key/certificate storage, Time Stamp Protocol (TSP), and PDF signature structures for comprehensive cryptographic messaging support.
class ContentInfo(core.Sequence): ...
class SignedData(core.Sequence): ...
class EnvelopedData(core.Sequence): ...
class Pfx(core.Sequence): ...
class TimeStampReq(core.Sequence): ...PEM encoding/decoding, low-level parsing utilities, cross-platform compatibility helpers, and version information. Includes functions for integer/byte conversion, network address handling, and timezone support.
def detect(byte_string): ...
def armor(type_name, der_bytes, headers=None): ...
def unarmor(pem_bytes, multiple=False): ...
def parse(contents, strict=False): ...All ASN.1 structures follow a consistent loading pattern:
from asn1crypto.x509 import Certificate
# Load from DER-encoded bytes
cert = Certificate.load(der_bytes)
# Access parsed data via .native property
cert_data = cert.native
# Access original encoded data via .dump()
original_der = cert.dump()Standard pattern for handling PEM-encoded data:
from asn1crypto import pem
# Detect PEM format
if pem.detect(data):
type_name, headers, der_bytes = pem.unarmor(data)
else:
der_bytes = data
# Convert DER back to PEM
pem_bytes = pem.armor('CERTIFICATE', der_bytes)The library uses specific exception types for different error conditions:
ValueError: Invalid ASN.1 structure or encodingTypeError: Incorrect parameter typesOSError: File I/O related errors (when applicable)class Asn1Value:
"""Base class for all ASN.1 values"""
def __init__(self, value=None, default=None): ...
@classmethod
def load(cls, encoded_data, strict=False): ...
def copy(self): ...
def retag(self, tagging, tag=None): ...
def untag(self): ...
def debug(self, nest_level=1): ...
def dump(self, force=False): ...
def cast(self, other_class): ...
@property
def native(self): ...
@property
def parsed(self): ...