ASN.1 describes structured values; DER is a binary encoding of them. This example writes a sequence and reads its integer and Boolean fields.
dotnet add package RecursiveAI.OneCrypto --prereleaseRequires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.
using RecursiveAI.OneCrypto.Asn1; var writer = new Asn1Writer(); writer.PushSequence(); writer.WriteInteger(42); writer.WriteBoolean(true); writer.Pop(); byte[] der = writer.Encode(); var reader = new Asn1Reader(der, Asn1Rules.Der); var sequence = reader.ReadSequence(); Console.WriteLine(sequence.ReadInteger()); Console.WriteLine(sequence.ReadBoolean()); sequence.ThrowIfNotEmpty(); reader.ThrowIfNotEmpty();
42 True
Unzip the example, then dotnet run.
The full program
The program also rejects a nonminimal DER integer.
using RecursiveAI.OneCrypto.Asn1; var writer = new Asn1Writer(); writer.PushSequence(); writer.WriteInteger(42); writer.WriteBoolean(true); writer.Pop(); byte[] der = writer.Encode(); var reader = new Asn1Reader(der, Asn1Rules.Der); var sequence = reader.ReadSequence(); Console.WriteLine(sequence.ReadInteger()); Console.WriteLine(sequence.ReadBoolean()); sequence.ThrowIfNotEmpty(); reader.ThrowIfNotEmpty(); Console.WriteLine(Convert.ToHexString(der)); var malformed = new Asn1Reader(new byte[] { 2, 2, 0, 1 }, Asn1Rules.Der); Console.WriteLine($"Nonminimal accepted: {malformed.TryReadInteger(out _)}"); Console.WriteLine($"Failure: {malformed.LastFailure}");
42 True 300602012A0101FF Nonminimal accepted: False Failure: Asn1Failure { Error = InvalidContent, Offset = 0, Message = The content is not a valid value of its type (offset 0). }
Malformed typed reads throw Asn1ParseException; the TryRead forms return false and record a reason and offset in LastFailure.
Variations
Read an unknown number of integers in a sequence.
using RecursiveAI.OneCrypto.Asn1; var writer = new Asn1Writer(); writer.PushSequence(); writer.WriteInteger(7); writer.WriteInteger(8); writer.Pop(); var reader = new Asn1Reader(writer.Encode(), Asn1Rules.Der); var sequence = reader.ReadSequence(); while (sequence.HasData) Console.WriteLine(sequence.ReadInteger()); reader.ThrowIfNotEmpty();
7 8
Related recipes
- Wrap and unwrap an AES key in C# (RFC 3394)
- Prepare and complete a detached signature in C#
- Sign and verify with Ed448 and a context in C#
The short answer
Use Asn1Writer to build the value and Asn1Reader with Asn1Rules.Der to decode it. Read a sequence through its child reader and check both readers for trailing data.
What does ASN.1 mean, and what is DER?
ASN.1 means Abstract Syntax Notation One. It describes data structures independently of a programming language; DER, or Distinguished Encoding Rules, defines a canonical binary encoding. The introduction from Let’s Encrypt explains the distinction with sequences, integers and certificate examples.
The example’s schema is a sequence containing an integer followed by a Boolean. It is deliberately not a certificate or a private-key file. The outer sequence tells the reader where the fields end; the application still has to know what those fields mean and which order the schema requires.
How do I encode ASN.1 DER in C#?
Create Asn1Writer, open a sequence, write the fields, close it with Pop and call Encode. The writer defaults to DER. The full program prints 300602012A0101FF: a sequence whose content is the encoded integer 42 and Boolean true. The writer calculates the enclosing length rather than requiring you to patch it manually.
The ASN.1 documentation also describes PushSetOf, which sorts the encoded members when the set closes. That is different from assigning semantic order to fields of an ordinary SET; the reader does not have an ASN.1 module and does not check ordinary SET tag order. A typed encoding API does not replace your schema.
How do I read an ASN.1 sequence in C#?
Create Asn1Reader over the input bytes with Asn1Rules.Der, then call ReadSequence. The returned reader is bounded to the sequence’s content. Read each typed field from that child and check it is empty when finished. Check the outer reader as well, so an unexpected second top-level value does not go unnoticed.
The explicit rules argument matters: the writer defaults to DER, but the reader defaults to BER. DER requires definite lengths in their shortest encoding, canonical Boolean true, and other restrictions described in the docs. Choosing BER to make a malformed DER input parse is not the same as validating it as DER.
Asn1Reader is a forward-only ref struct over a span. It is suitable for synchronous parsing of an in-memory value. The library also provides Asn1StreamReader for stream-based input; do not confuse a memory reader with a streaming parser simply because both move forward.
How do I detect malformed DER without an exception?
Use a typed TryRead method and inspect LastFailure immediately when it returns false. The full program gives the reader an INTEGER with an unnecessary leading zero. That is not a minimal integer encoding, so the typed read fails. The output includes the error category and offset.
Every failed TryRead leaves the reader’s position unchanged. Decide whether to reject the input or try a different schema branch; repeating the same read without advancing will fail again. The throwing twin reports the same reason and offset as Asn1ParseException.
Bounds are enabled by default through Asn1Limits, including nesting, total input and copied-value limits. A claimed element length is checked against remaining input before a slice or array is made. These checks do not establish that a parsed certificate is trusted or that a signature is valid. Use the format-specific certificate or signature APIs for those decisions rather than treating successful ASN.1 decoding as authentication.