Basic Encoding Rules

pyasn1.codec.ber.encoder.encode(value, asn1Spec=None, defMode=True, maxChunkSize=0)

Turns ASN.1 object into BER octet stream.

Takes any ASN.1 object (e.g. PyAsn1Item derivative) walks all its components recursively and produces a BER octet stream.

Parameters

value (either a Python or pyasn1 object (e.g. PyAsn1Item derivative)) – A Python or pyasn1 object to encode. If Python object is given, asnSpec parameter is required to guide the encoding process.

Keyword Arguments
  • asn1Spec – Optional ASN.1 schema or value object e.g. PyAsn1Item derivative

  • defMode (bool) – If False, produces indefinite length encoding

  • maxChunkSize (int) – Maximum chunk size in chunked encoding mode (0 denotes unlimited chunk size)

Returns

bytes (Python 3) or str (Python 2) – Given ASN.1 object encoded into BER octetstream

Raises

PyAsn1Error – On encoding errors

Examples

Encode Python value into BER with ASN.1 schema

>>> seq = SequenceOf(componentType=Integer())
>>> encode([1, 2, 3], asn1Spec=seq)
b'0\t\x02\x01\x01\x02\x01\x02\x02\x01\x03'

Encode ASN.1 value object into BER

>>> seq = SequenceOf(componentType=Integer())
>>> seq.extend([1, 2, 3])
>>> encode(seq)
b'0\t\x02\x01\x01\x02\x01\x02\x02\x01\x03'
pyasn1.codec.ber.decoder.decode(substrate, asn1Spec=None)

Turns BER octet stream into an ASN.1 object.

Takes BER octet-stream and decode it into an ASN.1 object (e.g. PyAsn1Item derivative) which may be a scalar or an arbitrary nested structure.

Parameters

substrate (bytes (Python 3) or str (Python 2)) – BER octet-stream

Keyword Arguments

asn1Spec (any pyasn1 type object e.g. PyAsn1Item derivative) – A pyasn1 type object to act as a template guiding the decoder. Depending on the ASN.1 structure being decoded, asn1Spec may or may not be required. Most common reason for it to require is that ASN.1 structure is encoded in IMPLICIT tagging mode.

Returns

tuple – A tuple of pyasn1 object recovered from BER substrate (PyAsn1Item derivative) and the unprocessed trailing portion of the substrate (may be empty)

Raises

PyAsn1Error, SubstrateUnderrunError – On decoding errors

Notes

This function is deprecated. Please use Decoder or StreamingDecoder class instance.

Examples

Decode BER serialisation without ASN.1 schema

>>> s, _ = decode(b'0\t\x02\x01\x01\x02\x01\x02\x02\x01\x03')
>>> str(s)
SequenceOf:
 1 2 3

Decode BER serialisation with ASN.1 schema

>>> seq = SequenceOf(componentType=Integer())
>>> s, _ = decode(b'0\t\x02\x01\x01\x02\x01\x02\x02\x01\x03', asn1Spec=seq)
>>> str(s)
SequenceOf:
 1 2 3