Skip to main content

Crate tc_asn1

Crate tc_asn1 

Source
Expand description

BER, CER and DER codecs for the ASN.1 universal types (X.690), for building the structures of X.509 and its neighbours on.

no_std with alloc; no macros, no I/O, and no dependencies unless an optional feature is on. Values are decoded from a slice and encoded into one, and every check is done on the structure before anything is allocated for it.

§What is here

§Decoding and encoding

Decode::decode accepts any BER; Decode::decode_der rejects with Asn1Error::NotDer whatever is not the canonical form. Both return the octets used, and neither complains about what follows. Encoding takes an EncodingOptions choosing BER, CER or DER; the three differ only where X.690 leaves a choice, see EncodingType. Limits on depth, length and element count come from DecodingOptions.

use tc_asn1::{Asn1Error, Asn1Integer, Asn1Object, Asn1SequenceOf, Decode, DecodingOptions, Encode, EncodingOptions, EncodingType};

// A SEQUENCE OF INTEGER, written under DER and read back.
let list = Asn1SequenceOf::new(vec![Asn1Integer::from(1), Asn1Integer::from(-1)]);
let der = list.encode_to_vec(&EncodingOptions::DER)?;
assert_eq!(der, [0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0xFF]);
let (used, back) = Asn1SequenceOf::<Asn1Integer>::decode(&der, &DecodingOptions::default())?;
assert_eq!((used, back), (8, list));

// The same octets without a schema, as a tree.
let (_, tree) = Asn1Object::decode(&der, &DecodingOptions::default())?;
assert_eq!(tree.to_string(), "SEQUENCE\n  INTEGER 1\n  INTEGER -1\n");

§Defining a structure

A SEQUENCE with fields uses two decoding implementations: DecodeContent opens Children::from_contents, reads the fields and calls Children::end; DecodeInner parses the outer element, checks its tag and delegates its contents to DecodeContent using the same context. This lets the field decoder also read the structure under an IMPLICIT tag.

EncodeContent writes the fields back to back, with empty Decode and EncodeTagged impls and small Encode and Tagged impls completing the type. A CHOICE dispatches on the tag in DecodeInner and on the variant in Encode. Each type states what it validates and whether it runs in constant time; nothing in this crate interprets secret data, so every method is variable time and documents it. The one exception is erasure: the Zeroize implementations below run in time that depends only on the size of what they wipe.

§Features

  • zeroize, off by default, implements tc_zeroize::Zeroize for every type that owns data, so a structure holding secret material, such as a private key, can erase the octets it decoded. It adds tc_zeroize.
  • chrono, off by default, converts Asn1UtcTime and Asn1GeneralizedTime to and from chrono::DateTime<Utc>. Going to chrono is exact, fractional seconds included; coming from it truncates to the second and turns a leap second into :59, and a year outside the type’s range is MalformedValue. It adds chrono, without its default features.
  • std, off by default, adds Encode::encode_to_writer, and the io module with Asn1Writer and Asn1Reader, which write encoded values to a std::io::Write and read them from a std::io::Read such as a file or a socket. It adds no dependency, only the standard library, so the crate is no longer no_std with it.

Zeroize is a capability, not a policy: no type here erases itself on drop, because none of them knows whether it holds a secret. A key container that does know implements Drop and ZeroizeOnDrop itself, calling zeroize on its fields. A zeroized value is still a valid value of its type and still encodes: integers, enumerations and REAL become zero, strings and containers become empty, identifiers become their shortest value (0.0, 0, /0), times the earliest value of their type, and an Asn1Any keeps its tag with empty contents.

§Not here

No derive macro or schema language, no streaming or incremental decoding, no constructed string segments beyond Asn1Constructed, and no knowledge of any particular protocol: the OIDs, the extensions and the profiles belong to the crates built on this one.

Modules§

io
Reading and writing encoded values over std::io.
tag
The identifier octets of the universal types (X.680 §8.4, X.690 §8.1.2).

Structs§

Arcs
The iterator from Asn1Oid::arcs.
Asn1Any
One complete TLV, stored byte for byte.
Asn1BitString
A bit string of any length, kept as packed octets plus the count of unused bits in the last one.
Asn1BmpString
Text within the Basic Multilingual Plane, written as UCS-2.
Asn1Boolean
A bool with the BOOLEAN encoding.
Asn1Constructed
A constructed encoding: an identifier and a series of T values.
Asn1Date
DATE: a Gregorian date in 1582-9999, written YYYY-MM-DD.
Asn1DateTime
DATE-TIME: YYYY-MM-DDThh:mm:ss, year 1582-9999, without zone or fraction.
Asn1Duration
DURATION: a P-prefixed duration; months are not converted to days.
Asn1Enumerated
An ENUMERATED value, kept as its two’s-complement content octets.
Asn1GeneralizedTime
A UTC instant to the nanosecond, year 0-9999.
Asn1Ia5String
Text in 7-bit ASCII.
Asn1Integer
An INTEGER of any size, kept as its two’s-complement content octets.
Asn1Null
The one NULL value.
Asn1NumericString
Digits and spaces.
Asn1OctetString
Arbitrary octets, the carrier of every opaque value from a key identifier to a whole encoded structure inside an extension.
Asn1Oid
An OBJECT IDENTIFIER, kept as its content octets.
Asn1OidIri
An absolute OID path starting with /; not a general URL.
Asn1PrintableString
Text in the PrintableString character set.
Asn1Real
A REAL, kept as its canonical DER contents in the base it was given.
Asn1Ref
One TLV borrowed from its buffer: the identifier, the contents and the end-of-contents octets if any.
Asn1RelativeOid
A RELATIVE-OID, kept as its content octets.
Asn1RelativeOidIri
A relative OID path without the leading /.
Asn1SequenceOf
A homogeneous SEQUENCE OF. Order is significant, so every rule set writes the elements as stored.
Asn1SetOf
A homogeneous SET OF. Construction and decoding keep the given order; CER and DER write the members sorted by their encodings (X.690 §11.6), BER writes them as stored.
Asn1Time
TIME: a date, time, interval, duration or recurring interval.
Asn1TimeOfDay
TIME-OF-DAY: hh:mm:ss without zone or fraction; end-of-day 24:00:00 is allowed.
Asn1UniversalString
Any Unicode text, written as UCS-4.
Asn1UtcTime
A UTC instant to the second, year 1950-2049.
Asn1Utf8String
Any Unicode text, written as UTF-8.
Asn1VisibleString
Printable ASCII, space included.
Children
The elements of a constructed value, one level deeper in the context.
DecodingContext
What a decoding in progress knows: the DecodingOptions with the limits, how deep in constructed values it currently is and whether the DER rules are being enforced.
DecodingOptions
Bounds on what a decoding may consume, so that untrusted input cannot drive memory or recursion beyond what the caller planned for.
EncodingOptions
The choices an encoding is made under, passed to every Encode and EncodeContent call so that nested values follow the same rules as the outer one.
Explicit
[n] EXPLICIT T: the value’s complete TLV wrapped in a constructed element with the given tag, A0 03 02 01 02 for [0] EXPLICIT INTEGER 2.
Implicit
[n] IMPLICIT T: the value’s own identifier replaced by the given tag, contents unchanged, 81 02 05 A0 for [1] IMPLICIT BIT STRING.
NamedOid
An OID fixed at compile time, with its dotted form and a name: the building block of constant tables such as attribute types or key purposes. Comparing one against a decoded Asn1Oid works on the DER content octets and allocates nothing.

Enums§

Asn1Class
The class bits of an identifier octet (X.690 §8.1.2.2).
Asn1Error
Why a decode, an encode or a conversion failed.
Asn1Object
Any BER value as a tree: each universal type as its own variant, a constructed value under any other tag as Constructed and an uninterpreted primitive as Unknown.
EncodingType
The rule set an encoder follows, X.690 §8 to §11. Decoding needs no such choice: it accepts every form and can additionally insist on DER, see DecodingContext::new_der.
LengthForm
How a constructed value’s length is written under BER (X.690 §8.1.3).

Traits§

Decode
The standalone entry points: a fresh context per call, BER-lenient or DER. Implemented as impl Decode for T {} on top of DecodeInner.
DecodeContent
Reads the contents octets of a primitive encoding, the tag and length having been consumed by the caller.
DecodeInner
Reads one complete TLV under the type’s own tag, inside a decoding already in progress.
Encode
Writes a complete TLV under the type’s own tag: the method a SEQUENCE calls for each of its fields and the one callers use directly.
EncodeContent
Writes the contents octets: the value without its tag and length.
EncodeTagged
Writes a complete TLV under a tag the caller chooses.
Tagged
The tag a type reads and writes on its own, as the identifier octets.