pyasn1

raw JSON →
0.6.3 verified Tue May 12 auth: no python install: verified quickstart: verified

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.

pip install pyasn1
error ModuleNotFoundError: No module named 'pyasn1'
cause The `pyasn1` library is not installed in the Python environment being used, or there's a Python version conflict (e.g., installed for Python 2 but running Python 3).
fix
Ensure pyasn1 is installed for the correct Python interpreter: pip install pyasn1 or python -m pip install pyasn1.
error ModuleNotFoundError: No module named 'pyasn1.codec.der.decoder'
cause This specific submodule of `pyasn1` (or another submodule like `pyasn1.type.univ`) cannot be found, often due to an incomplete or corrupted `pyasn1` installation, or an environment path issue.
fix
Reinstall or upgrade pyasn1: pip install --upgrade pyasn1 or python -m pip install --upgrade pyasn1. If using an older Python version or specific distribution packages, ensure the correct pyasn1 package (e.g., python3-pyasn1 on Debian/Ubuntu) is installed.
error AttributeError: 'NoneType' object has no attribute 'tagSet'
cause This typically occurs during ASN.1 decoding when `pyasn1` fails to parse a part of the input data, resulting in `None` being returned for an expected ASN.1 object, and subsequent code attempts to access attributes (like `tagSet`) on this `None` object. This usually indicates malformed input data or a mismatch with the provided ASN.1 schema.
fix
Verify the input BER/DER/CER encoded data is well-formed and matches the ASN.1 specification (asn1Spec) used for decoding. Debug the decoding process to identify the exact malformed segment or schema mismatch.
error pyasn1.error.PyAsn1Error: Type TagSet(...) not found in asn1Spec
cause This error arises when `pyasn1` attempts to decode an ASN.1 object, but the tag set identified in the input byte stream does not correspond to any type defined in the `asn1Spec` provided to the decoder.
fix
Ensure the asn1Spec passed to the decoder accurately reflects the structure and tags of the ASN.1 data being decoded. The error message will often show the unexpected TagSet, which can help in correcting the schema.
error TypeError: __init__() takes 1 positional argument but 2 were given
cause This error often indicates an API incompatibility, particularly between different versions of `pyasn1` or when `pyasn1-modules` is used with an incompatible `pyasn1` version. Older `pyasn1` versions (e.g., pre-0.3.1) might have had constructors with different signatures than newer ones, especially for types like `univ.SequenceOf` or `SetOf` when defining components.
fix
Upgrade both pyasn1 and pyasn1-modules to their latest compatible versions (pip install --upgrade pyasn1 pyasn1-modules). If the issue persists with the latest versions, check the pyasn1 changelog for breaking API changes related to the specific class being instantiated and adjust your code accordingly.
breaking decode() always returns a 2-tuple (asn1Object, remainingSubstrate). Ignoring the second element or trying to use the result directly as the decoded value is the single most common runtime bug.
fix Always unpack: `value, remainder = decode(substrate, asn1Spec=MyType())`; check `remainder == b''` to detect trailing garbage.
breaking Python 2 and Python < 3.8 support dropped in v0.6.0. The PyPI package now requires Python >=3.8.
fix Upgrade to Python 3.8+ and pin pyasn1>=0.6.0. Remove any Python 2 compatibility shims (six, future) from your codebase.
breaking SequenceOf/SetOf instances are no longer auto-initialised as value objects on instantiation (changed in 0.4.x). Code that tested `if mySeqOf:` or iterated an empty SequenceOf immediately after construction will silently get wrong results or raise errors.
fix Call `.clear()` on a SequenceOf/SetOf instance to explicitly make it a value object (empty list), or append a component first. Do not assume an empty SequenceOf is a value object.
breaking The substrateFun callback signature changed in v0.5.0 from non-streaming (v0.4 style) to streaming. The v0.5.1 patch restores transparent compatibility for decoder.decode(), but custom substrateFun callbacks passed to low-level streaming decoders must use the new streaming signature.
fix If passing substrateFun to the top-level `decoder.decode()`, both old and new signatures work as of 0.5.1+. For streaming decoders directly, migrate to the v0.5 streaming callback signature.
gotcha Without asn1Spec=, the decoder falls back to generic BER decoding and returns untyped Any objects. IMPLICIT tags cannot be decoded without a spec, so fields will silently be missing or mis-typed.
fix Always pass `asn1Spec=MySchemaType()` to decode(). This is mandatory for any schema that uses IMPLICIT or EXPLICIT tagging.
gotcha Pre-built ASN.1 modules (X.509 RFC 5280, PKCS, SNMP MIBs, etc.) were moved to the separate pyasn1-modules package long ago and are no longer included in pyasn1 itself.
fix Install pyasn1-modules separately: `pip install pyasn1-modules`. Import e.g. `from pyasn1_modules import rfc5280`.
gotcha pyasn1 types mimic Python built-ins (Integer ≈ int, OctetString ≈ bytes) but comparisons, hashing, and arithmetic can differ subtly. Passing a raw Python int where an Integer() instance is expected often works, but not always — especially inside Sequence field assignment with constraints.
fix Explicitly wrap values: `record['id'] = Integer(123)` rather than relying on implicit coercion. Use `.hasValue()` / `.isValue` to check whether a component has been populated before encoding.
pip install pyasn1 pyasn1-modules
python os / libc status wheel install import disk
3.10 alpine (musl) - - 0.01s 18.6M
3.10 alpine (musl) - - 0.01s 20.5M
3.10 slim (glibc) - - 0.01s 19M
3.10 slim (glibc) - - 0.01s 21M
3.11 alpine (musl) - - 0.01s 20.6M
3.11 alpine (musl) - - 0.01s 23.1M
3.11 slim (glibc) - - 0.01s 21M
3.11 slim (glibc) - - 0.01s 24M
3.12 alpine (musl) - - 0.01s 12.5M
3.12 alpine (musl) - - 0.01s 14.9M
3.12 slim (glibc) - - 0.01s 13M
3.12 slim (glibc) - - 0.01s 15M
3.13 alpine (musl) - - 0.01s 12.1M
3.13 alpine (musl) - - 0.01s 14.5M
3.13 slim (glibc) - - 0.01s 13M
3.13 slim (glibc) - - 0.01s 15M
3.9 alpine (musl) - - 0.01s 18.2M
3.9 alpine (musl) - - 0.01s 20.1M
3.9 slim (glibc) - - 0.01s 19M
3.9 slim (glibc) - - 0.01s 21M

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())