ASN.1 and DER: a strict encoder and decoder

A strict DER (Distinguished Encoding Rules) codec: the byte layer every X.509 / PKCS / CMS structure is built on. The decoder is fail-closed: it rejects the BER shapes DER forbids (indefinite length, non-minimal length or integer encodings, trailing garbage, constructed strings) and refuses input past a size or nesting cap before it walks a single byte, so a hostile length prefix can't turn into a decoder denial-of-service.

decode(bytes) returns a navigable node tree; the read.* helpers turn a node into a JS value (BigInt, dotted OID, Date, string); the build.* helpers construct canonical DER from JS values. Because DER is canonical, each value the build.* helpers emit has exactly one valid encoding, byte-identical to any other conformant DER encoder's output, and decoding it reproduces the value it was built from. build.generalizedTime(date) emits whole seconds, the RFC 5280 form; build.generalizedTime(date, { fractional: true }) keeps the Date's milliseconds in the X.690 DER fraction (no trailing zeros, no empty fraction), the form RFC 3161 allows a timestamp's genTime, which read.time(node, { allowFractional: true }) reads back.

pki.asn1.reservedUniversalTag

since 0.8.54 stable
pki.asn1.reservedUniversalTag(tagNumber) -> boolean

Whether X.680 reserves this universal tag number, which means no ASN.1 type is assigned to it and no DER encoding of any type uses it. Table 1 reserves three rows: tag 0 for the encoding rules, tag 15 for future editions of the Recommendation, and tag 37 upward for its addenda. decode refuses an element carrying any of them with asn1/reserved-tag, so this answers the same question ahead of the attempt.

The question is not "does this codec have a reader for the tag", which is a smaller set: ObjectDescriptor (7), REAL (9), RELATIVE-OID (13), the time type (14), VideotexString (21), GraphicString (25) and GeneralString (27) are all assigned by X.680 and all arrive here as opaque values, and each is legitimate inside an ANY. This returns false for every one of them.

Example

pki.asn1.reservedUniversalTag(0);    // -> true   (the encoding rules)
pki.asn1.reservedUniversalTag(15);   // -> true   (future editions)
pki.asn1.reservedUniversalTag(37);   // -> true   (addenda)
pki.asn1.reservedUniversalTag(9);    // -> false  (REAL, assigned, no reader here)
pki.asn1.reservedUniversalTag(31);   // -> false  (DATE, assigned)

References

  • spec X.680
  • spec ISO/IEC 8824-1

pki.asn1.decode

since 0.1.0 stable
pki.asn1.decode(bytes, opts?) -> node

Parse DER into a node tree. Each node is { tagClass, constructed, tagNumber, header, length, content, children, bytes, contentStart, contentEnd }, where content is the primitive value slice, children the decoded sub-nodes of a constructed node, bytes the full TLV slice, and contentStart / contentEnd the content slice's byte offsets in the input (all slices are zero-copy views over the input).

Throws Asn1Error on any non-DER shape: indefinite length, a non-minimal length or a length that overruns the buffer, trailing bytes after the top-level value (unless allowTrailing), or exceeding the size / depth caps.

ber: true is a scoped relaxation for formats whose content regions are normatively BER (RFC 7292 PKCS#12): it accepts an indefinite length on a constructed value and a constructed OCTET STRING, whose segments are reassembled into one primitive content. Nothing else is relaxed: definite lengths stay minimal, an indefinite length on a primitive value and a foreign-type segment still reject, and the size / depth caps hold.

Options

maxBytes:       number,   // default: C.LIMITS.DER_MAX_BYTES (16 MiB)
maxDepth:       number,   // default: C.LIMITS.DER_MAX_DEPTH (64)
maxItems:       number,   // default: C.LIMITS.DER_MAX_ITEMS (total decoded node cap)
allowTrailing:  boolean,  // default false; allow bytes after the top TLV
ber:            boolean,  // default false; accept indefinite lengths +
                          // constructed OCTET STRINGs (BER content regions)

Example

var der = pki.asn1.build.sequence([pki.asn1.build.integer(1n)]);
var node = pki.asn1.decode(der);
node.tagNumber === pki.asn1.TAGS.SEQUENCE;

References

  • spec X.690
  • spec ISO/IEC 8825-1
  • defends ASN.1-parser-DoS (CWE-400)

pki.asn1.read.oid

since 0.1.15 originated 0.1.0 stable
pki.asn1.read.oid(node) -> "1.2.840.113549.1.1.11"

Decode an OBJECT IDENTIFIER node to its dotted-decimal string, enforcing the minimal base-128 sub-identifier encoding DER requires.

Example

var node = pki.asn1.decode(pki.asn1.build.oid("2.5.4.3"));
pki.asn1.read.oid(node); // -> "2.5.4.3"

References

pki.asn1.encode

since 0.1.0 stable
pki.asn1.encode(classBits, constructed, tagNumber, content) -> Buffer

Low-level TLV encoder: prepend the identifier + DER length to a content buffer. Most callers use the higher-level build.* helpers; this is the escape hatch for context-tagged and implicitly-tagged constructions.

classBits is a number naming a class: 0x00 universal, 0x40 application, 0x80 context or 0xc0 private, with 0x20 constructed allowed alongside. Anything else is asn1/bad-tag, because the low five bits of this argument are written into a single-octet identifier and a value carrying any of them emits a tag other than the one passed.

A universal-class tag number that X.680 Table 1 reserves is refused with asn1/reserved-tag, the code pki.asn1.decode gives the same bytes, so the escape hatch cannot author an element the decoder calls malformed. Ask pki.asn1.reservedUniversalTag which numbers those are. Every other class takes any tag number the 4-octet high-tag form holds, a context [15] included; past that form the code is asn1/tag-too-large, as it is on the way in. The DER form restrictions are not applied here: a constructed OCTET STRING or character string is a legal BER encoding, and this is the door it is written through.

Example

pki.asn1.encode(0x00, false, pki.asn1.TAGS.NULL, Buffer.alloc(0));

References

  • spec X.690
  • spec ISO/IEC 8825-1

pki.asn1.build

since 0.1.0 stable
pki.asn1.build.sequence([ ...tlvBuffers ]) -> Buffer

Canonical-DER value builders. Each returns the full TLV Buffer for one value; sequence / set / setOf take arrays of already-built child TLVs. setOf sorts its members by their DER encoding as X.690 requires.

Example

var rdn = pki.asn1.build.sequence([
  pki.asn1.build.oid("2.5.4.3"),
  pki.asn1.build.utf8("example.com"),
]);

References

  • spec X.690
  • spec ISO/IEC 8825-1