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
-
The universal types, each as its own struct:
Asn1Integer,Asn1Oid,Asn1BitString, the string types, the time types,Asn1SequenceOfandAsn1SetOf, and so on. Each keeps the value the way the wire does (an INTEGER as its octets, a SET OF in the order given) and applies the DER rules on output and, when asked, on input. -
The structural layer for reading without a schema:
Asn1Reffor one TLV,Childrenfor the elements of a constructed one,Asn1Anyto keep an element as octets,Asn1Constructedfor a constructed value under any tag,Asn1Objectfor a whole decoded tree. -
The traits a structure implements to become a type of its own, in three layers so that the tagging wrappers and the containers can reuse them:
Layer Decoding Encoding The contents octets, given the tag and length DecodeContentEncodeContentA complete TLV under a caller-chosen tag — EncodeTaggedA complete TLV under the type’s own tag DecodeInnerEncodeThe standalone entry points Decode— DecodeContentreads the fields andEncodeContentwrites them;DecodeInnerchecks the outer TLV before delegating toDecodeContent.Taggednames the type’s own tag.ExplicitandImplicitwrite tagged fields,Children::get_explicit_optand friends read them. -
NamedOidfor constant tables of OIDs with names, checked when compiled.
§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, implementstc_zeroize::Zeroizefor every type that owns data, so a structure holding secret material, such as a private key, can erase the octets it decoded. It addstc_zeroize.chrono, off by default, convertsAsn1UtcTimeandAsn1GeneralizedTimeto and fromchrono::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 isMalformedValue. It addschrono, without its default features.std, off by default, addsEncode::encode_to_writer, and theiomodule withAsn1WriterandAsn1Reader, which write encoded values to astd::io::Writeand read them from astd::io::Readsuch as a file or a socket. It adds no dependency, only the standard library, so the crate is no longerno_stdwith 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.
- Asn1
BitString - A bit string of any length, kept as packed octets plus the count of unused bits in the last one.
- Asn1
BmpString - Text within the Basic Multilingual Plane, written as UCS-2.
- Asn1
Boolean - A
boolwith the BOOLEAN encoding. - Asn1
Constructed - A constructed encoding: an identifier and a series of
Tvalues. - Asn1
Date - DATE: a Gregorian date in 1582-9999, written
YYYY-MM-DD. - Asn1
Date Time - DATE-TIME:
YYYY-MM-DDThh:mm:ss, year 1582-9999, without zone or fraction. - Asn1
Duration - DURATION: a
P-prefixed duration; months are not converted to days. - Asn1
Enumerated - An ENUMERATED value, kept as its two’s-complement content octets.
- Asn1
Generalized Time - A UTC instant to the nanosecond, year 0-9999.
- Asn1
Ia5String - Text in 7-bit ASCII.
- Asn1
Integer - An INTEGER of any size, kept as its two’s-complement content octets.
- Asn1
Null - The one NULL value.
- Asn1
Numeric String - Digits and spaces.
- Asn1
Octet String - 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.
- Asn1
OidIri - An absolute OID path starting with
/; not a general URL. - Asn1
Printable String - Text in the PrintableString character set.
- Asn1
Real - 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.
- Asn1
Relative Oid - A RELATIVE-OID, kept as its content octets.
- Asn1
Relative OidIri - A relative OID path without the leading
/. - Asn1
Sequence Of - A homogeneous SEQUENCE OF. Order is significant, so every rule set writes the elements as stored.
- Asn1
SetOf - 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.
- Asn1
Time - TIME: a date, time, interval, duration or recurring interval.
- Asn1
Time OfDay - TIME-OF-DAY:
hh:mm:sswithout zone or fraction; end-of-day24:00:00is allowed. - Asn1
Universal String - Any Unicode text, written as UCS-4.
- Asn1
UtcTime - A UTC instant to the second, year 1950-2049.
- Asn1
Utf8 String - Any Unicode text, written as UTF-8.
- Asn1
Visible String - Printable ASCII, space included.
- Children
- The elements of a constructed value, one level deeper in the context.
- Decoding
Context - What a decoding in progress knows: the
DecodingOptionswith the limits, how deep in constructed values it currently is and whether the DER rules are being enforced. - Decoding
Options - Bounds on what a decoding may consume, so that untrusted input cannot drive memory or recursion beyond what the caller planned for.
- Encoding
Options - The choices an encoding is made under, passed to every
EncodeandEncodeContentcall 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 02for[0] EXPLICIT INTEGER 2.- Implicit
[n] IMPLICIT T: the value’s own identifier replaced by the given tag, contents unchanged,81 02 05 A0for[1] IMPLICIT BIT STRING.- Named
Oid - 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
Asn1Oidworks on the DER content octets and allocates nothing.
Enums§
- Asn1
Class - The class bits of an identifier octet (X.690 §8.1.2.2).
- Asn1
Error - Why a decode, an encode or a conversion failed.
- Asn1
Object - Any BER value as a tree: each universal type as its own variant, a
constructed value under any other tag as
Constructedand an uninterpreted primitive asUnknown. - Encoding
Type - 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. - Length
Form - 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 ofDecodeInner. - Decode
Content - Reads the contents octets of a primitive encoding, the tag and length having been consumed by the caller.
- Decode
Inner - 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.
- Encode
Content - Writes the contents octets: the value without its tag and length.
- Encode
Tagged - 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.