2. PyASN1 Codecs
In ASN.1 context, codec is a program that transforms between concrete data structures and a stream of octets, suitable for transmission over the wire. This serialized form of data is sometimes called substrate or essence.
In pyasn1 implementation, substrate takes shape of Python 3 bytes or Python 2 string objects.
One of the properties of a codec is its ability to cope with incomplete data and/or substrate what implies codec to be stateful. In other words, when decoder runs out of substrate and data item being recovered is still incomplete, stateful codec would suspend and complete data item recovery whenever the rest of substrate becomes available. Similarly, stateful encoder would encode data items in multiple steps waiting for source data to arrive. Codec restartability is especially important when application deals with large volumes of data and/or runs on low RAM. For an interesting discussion on codecs options and design choices, refer to Apache ASN.1 project .
As of this writing, codecs implemented in pyasn1 are all stateless, mostly to keep the code simple.
Encoder is used for transforming pyasn1 value objects into substrate. Only pyasn1 value objects could be serialized, attempts to process pyasn1 type objects will cause encoder failure.
The following code will create a pyasn1 Integer object and serialize it with BER encoder:
BER standard also defines a so-called indefinite length encoding form which makes large data items processing more memory efficient. It is mostly useful when encoder does not have the whole value all at once and the length of the value can not be determined at the beginning of encoding.
Constructed encoding is another feature of BER closely related to the indefinite length form. In essence, a large scalar value (such as ASN.1 character BitString type) could be chopped into smaller chunks by encoder and transmitted incrementally to limit memory consumption. Unlike indefinite length case, the length of the whole value must be known in advance when using constructed, definite length encoding form.
Since pyasn1 codecs are not restartable, pyasn1 encoder may only encode data item all at once. However, even in this case, generating indefinite length encoding may help a low-memory receiver, running a restartable decoder, to process a large data item.
The defMode encoder parameter disables definite length encoding mode, while the optional maxChunkSize parameter specifies desired substrate chunk size that influences memory requirements at the decoder's end.
To use CER or DER encoders one needs to explicitly import and call them - the APIs are all compatible.
In the process of decoding, pyasn1 value objects are created and linked to each other, based on the information containted in the substrate. Thus, the original pyasn1 value object(s) are recovered.
Commenting on the code snippet above, pyasn1 decoder accepts substrate as an argument and returns a tuple of pyasn1 value object (possibly a top-level one in case of constructed object) and unprocessed part of input substrate.
All pyasn1 decoders can handle both definite and indefinite length encoding modes automatically, explicit switching into one mode to another is not required.
Speaking of BER/CER/DER encoding, in many situations substrate may not contain all necessary information needed for complete and accurate ASN.1 values recovery. The most obvious cases include implicitly tagged ASN.1 types and constrained types.
As discussed earlier in this handbook, when an ASN.1 type is implicitly tagged, previous outermost tag is lost and never appears in substrate. If it is the base tag that gets lost, decoder is unable to pick type-specific value decoder at its table of built-in types, and therefore recover the value part, based only on the information contained in substrate. The approach taken by pyasn1 decoder is to use a prototype pyasn1 type object (or a set of them) to guide the decoding process by matching [possibly incomplete] tags recovered from substrate with those found in prototype pyasn1 type objects (also called pyasn1 specification object further in this paper).
Decoder would neither modify pyasn1 specification object nor use its current values (if it's a pyasn1 value object), but rather use it as a hint for choosing proper decoder and as a pattern for creating new objects:
Notice in the example above, that an attempt to run decoder without passing pyasn1 specification object fails because recovered tag does not belong to any of the built-in types.
Another important feature of guided decoder operation is the use of values constraints possibly present in pyasn1 specification object. To explain this, we will decode a random integer object into generic Integer and the constrained one.
Similarily to encoders, to use CER or DER decoders application has to explicitly import and call them - all APIs are compatible.
2.2.1 Decoding untagged types
It has already been mentioned, that ASN.1 has two "special case" types: CHOICE and ANY. They are different from other types in part of tagging - unless these two are additionally tagged, neither of them will have their own tag. Therefore these types become invisible in substrate and can not be recovered without passing pyasn1 specification object to decoder.
To explain the issue, we will first prepare a Choice object to deal with:
Let's now encode this Choice object and then decode its substrate with and without pyasn1 specification object:
First thing to notice in the listing above is that the substrate produced for our Choice value object is equivalent to the substrate for an OctetString object initialized to the same value. In other words, any information about the Choice component is absent in encoding.
Sure enough, that kind of substrate will decode into an OctetString object, unless original Choice type object is passed to decoder to guide the decoding process.
Similarily untagged ANY type behaves differently on decoding phase - when decoder bumps into an Any object in pyasn1 specification, it stops decoding and puts all the substrate into a new Any value object in form of an octet string. Concerned application could then re-run decoder with an additional, more exact pyasn1 specification object to recover the contents of Any object.
As it was mentioned elsewhere in this paper, Any type allows for incomplete or changing ASN.1 specification to be handled gracefully by decoder and applications.
To illustrate the working of Any type, we'll have to make the stage by encoding a pyasn1 object and then putting its substrate into an any object.
As with Choice type encoding, there is no traces of Any type in substrate. Obviously, the substrate we are dealing with, will decode into the inner [Integer] component, unless pyasn1 specification is given to guide the decoder. Continuing previous code:
Both CHOICE and ANY types are widely used in practice. Reader is welcome to take a look at ASN.1 specifications of X.509 applications for more information.
2.2.2 Ignoring unknown types
When dealing with a loosely specified ASN.1 structure, the receiving end may not be aware of some types present in the substrate. It may be convenient then to turn decoder into a recovery mode. Whilst there, decoder will not bail out when hit an unknown tag but rather treat it as an Any type.
It's also possible to configure a custom decoder, to handle unknown tags found in substrate. This can be done by means of defaultRawDecoder attribute holding a reference to type decoder object. Refer to the source for API details.