Registry / serialization / pyasn1

pyasn1

JSON →
library0.6.4pypypi✓ verified 27d ago

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
INSTALL
IMPORT
SIG · PYASN1
P
pyasn1
serializationpythonv0.6.4
Install
1.8s avg
Import
10ms
Disk
19MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.6.4 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.910 runs
installs and imports cleanly · install 0.0s · import 0.010s · 20.5MB
glibc
py 3.103.910 runs
installs and imports cleanly · install 1.8s · import 0.010s · 21MB
19MB installed
● package 19MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Integer, OctetString, ObjectIdentifier
from pyasn1.type.univ import Integer, OctetString, ObjectIdentifier
All primitive ASN.1 scalar types live in pyasn1.type.univ
Sequence, SequenceOf, Set, SetOf, Choice
from pyasn1.type.univ import Sequence, SequenceOf, Set, SetOf, Choice
Structured/constructed types also in pyasn1.type.univ
NamedType, OptionalNamedType, DefaultedNamedType, NamedTypes
from pyasn1.type.namedtype import NamedType, OptionalNamedType, DefaultedNamedType, NamedTypes
Required when declaring SEQUENCE field names; wrong module is a common ImportError
Tag, tagClassContext, tagFormatSimple
from pyasn1.type.tag import Tag, tagClassContext, tagFormatSimple
Used with .subtype(implicitTag=...) or .subtype(explicitTag=...) for context tagging
encode (DER)
from pyasn1.codec.der.encoder import encode
from pyasn1.codec.ber.encoder import encode
Use the DER encoder for certificates and strict protocols; BER allows non-canonical forms that some validators reject
decode (DER)
from pyasn1.codec.der.decoder import decode
Always unpack as (value, remainder) — decode() returns a 2-tuple, not just the value
encode/decode (BER)
from pyasn1.codec.ber.encoder import encode from pyasn1.codec.ber.decoder import decode
BER is the permissive superset; use for parsing untrusted or legacy inputs where indefinite length is possible
encode/decode (native Python dicts)
from pyasn1.codec.native.encoder import encode from pyasn1.codec.native.decoder import decode
Converts pyasn1 objects to/from plain Python dicts/lists/ints; useful for JSON interop
PyAsn1Error
from pyasn1.error import PyAsn1Error
Base exception for all pyasn1 errors; catch this for encoder/decoder failures

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())
Debug
Known issues
breakingdecode() 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.
affects: all
breakingPython 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.
affects: <0.6.0
breakingSequenceOf/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.
affects: >=0.4.0
breakingThe 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.
affects: 0.5.0
gotchaWithout 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.
affects: all
gotchaPre-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`.
affects: >=0.3.0
gotchapyasn1 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.
affects: all
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'pyasn1'
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`.
ModuleNotFoundError: No module named 'pyasn1.codec.der.decoder'
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.
AttributeError: 'NoneType' object has no attribute 'tagSet'
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.
pyasn1.error.PyAsn1Error: Type TagSet(...) not found in asn1Spec
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.
TypeError: __init__() takes 1 positional argument but 2 were given
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.
Upgrade
Version history
0.6.4latest on PyPI · released Jul 9, 2026
Audit
Dependencies
pyasn1-modulesoptionalPre-compiled ASN.1 schemas for standard protocols (RFC 2459/5280 X.509, PKCS#1/8/12, SNMP MIBs, etc.). Not bundled since v0.3.x.
Agent activity
11 hits · last 30 days
node
8
OpenAI (training)
1
Resources
pyasn1 — pip install pyasn1 · libregistry