pyasn1

0.6.3 · active · verified Sat Mar 28

pyasn1 is a pure-Python implementation of ASN.1 types and BER/DER/CER codecs (X.208). It lets developers define ASN.1 schemas as Python classes, then encode/decode wire-format bytes for network protocols and file formats such as X.509 certificates, PKCS structures, SNMP, and LDAP. Current version is 0.6.3 (released 2026), which adds a nesting depth limit to prevent stack overflow (CVE-2026-30922) and fixes an OverflowError from oversized BER length fields. The project is maintained by Christian Heimes and Simon Pichugin under the github.com/pyasn1 organisation following ownership transfer at v0.5.0; releases are irregular but active, with multiple releases per year addressing security CVEs and Python version support.

Warnings

Install

Imports

Quickstart

Define an ASN.1 SEQUENCE schema, populate it, DER-encode it, then decode it back and verify round-trip equality.

from pyasn1.type.univ import Sequence, Integer
from pyasn1.type.namedtype import NamedType, OptionalNamedType, DefaultedNamedType, NamedTypes
from pyasn1.type.tag import Tag, tagClassContext, tagFormatSimple
from pyasn1.codec.der.encoder import encode
from pyasn1.codec.der.decoder import decode
from pyasn1.error import PyAsn1Error

# 1. Define ASN.1 schema as a Python class
class Record(Sequence):
    componentType = NamedTypes(
        NamedType('id', Integer()),
        OptionalNamedType(
            'room',
            Integer().subtype(implicitTag=Tag(tagClassContext, tagFormatSimple, 0))
        ),
        DefaultedNamedType(
            'house',
            Integer(0).subtype(implicitTag=Tag(tagClassContext, tagFormatSimple, 1))
        ),
    )

# 2. Populate the schema object
record = Record()
record['id'] = 123
record['room'] = 321

# 3. DER-encode to bytes
substrate = encode(record)
print('DER bytes:', substrate.hex())  # e.g. 30070201 7b800201 41

# 4. Decode back — ALWAYS unpack the 2-tuple (value, remainder)
try:
    received, remainder = decode(substrate, asn1Spec=Record())
except PyAsn1Error as exc:
    raise SystemExit(f'Decode failed: {exc}')

assert remainder == b'', 'Unexpected trailing bytes'
assert received['id'] == record['id']
print('Round-trip OK:', received.prettyPrint())

view raw JSON →