---
title: "Read and write ASN.1 DER in C#"
url: https://recursiveai.org/onecrypto/cookbook/read-write-asn1-der/
description: "Read and write ASN.1 DER in C#: runnable .NET 10 example with OneCrypto, actual output and a downloadable project."
version: "0.4.0-preview.2"
---

# Read and write ASN.1 DER in C#

**OneCrypto** is a free, open-source cryptography library for .NET from Recursive AI. MIT or Apache-2.0, preview, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneCrypto) · [GitHub](https://github.com/recursive-ai-oss/onecrypto-csharp) · [Docs](https://recursiveai.org/onecrypto/docs/) · [Download example (.zip)](https://recursiveai.org/onecrypto/cookbook/read-write-asn1-der/read-write-asn1-der.zip)

ASN.1 describes structured values; DER is a binary encoding of them. This example writes a sequence and reads its integer and Boolean fields.

```shell
dotnet add package RecursiveAI.OneCrypto --prerelease
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
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();
```

```text
42
True
```

Unzip [the example](https://recursiveai.org/onecrypto/cookbook/read-write-asn1-der/read-write-asn1-der.zip), then `dotnet run`.

## The full program

The program also rejects a nonminimal DER integer.

```csharp
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}");
```

```text
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.

```csharp
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();
```

```text
7
8
```

## Related recipes

- [Wrap and unwrap an AES key in C# (RFC 3394)](https://recursiveai.org/onecrypto/cookbook/wrap-unwrap-aes-key-rfc3394/)
- [Prepare and complete a detached signature in C#](https://recursiveai.org/onecrypto/cookbook/prepare-and-complete-detached-signature/)
- [Sign and verify with Ed448 and a context in C#](https://recursiveai.org/onecrypto/cookbook/ed448-sign-verify/)

---

## 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](https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/) 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](https://recursiveai.org/onecrypto/docs/asn1/) 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.
