Distinguished Encoding Rules¶
-
pyasn1.codec.der.encoder.encode(value, asn1Spec=None)¶ Turns ASN.1 object into DER octet stream.
Takes any ASN.1 object (e.g.
PyAsn1Itemderivative) walks all its components recursively and produces a DER octet stream.Parameters: value (either a Python or pyasn1 object (e.g. PyAsn1Itemderivative)) – 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. PyAsn1ItemderivativeReturns: bytes(Python 3) orstr(Python 2) – Given ASN.1 object encoded into BER octet-streamRaises: PyAsn1Error– On encoding errorsExamples
Encode Python value into DER 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 DER
>>> 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.der.decoder.decode(substrate, asn1Spec=None)¶ Turns DER octet stream into an ASN.1 object.
Takes DER octet-stream and decode it into an ASN.1 object (e.g.
PyAsn1Itemderivative) which may be a scalar or an arbitrary nested structure.Parameters: substrate ( bytes(Python 3) orstr(Python 2)) – DER octet-streamKeyword Arguments: asn1Spec (any pyasn1 type object e.g. PyAsn1Itemderivative) – 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 DER substrate (PyAsn1Itemderivative) and the unprocessed trailing portion of the substrate (may be empty)Raises: PyAsn1Error– On decoding errorsExamples
Decode DER 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 DER 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