Abstract Syntax Notation One (ASN.1) is a standard and notation that describes rules and structures for representing, encoding, transmitting, and decoding data in telecommunications and computer networking. ASN1js is a pure JavaScript library implementing this standard. ASN.1 is the basis of all X.509 related data structures and numerous other protocols used on the web.
npm install asn1jsDocumentation, the API reference, and runnable examples are at asn1js.org.
v4 is ESM-only and requires Node.js ^20.19.0 || >=22.12.0 (was >=12.0.0). CommonJS code can still require("asn1js") on these versions; Node.js 22.0–22.11 can't. The existing exported API remains compatible, but some encoding and validation behavior changed (last three items).
- TypeScript compiling to CommonJS: use
"module": "node20"or"nodenext"(node16fails with TS1479). ESM and bundler setups need no changes. - Jest in CommonJS mode: switch to ESM mode or Vitest, or configure an ESM-to-CommonJS transformer and make sure
transformIgnorePatternsdoesn't excludeasn1jsand its ESM dependencies, such as@peculiar/utils. - Deep imports (
asn1js/build/index.js,asn1js/build/index.es.js) are blocked byexports; import fromasn1js. - One asn1js per app: libraries such as
pkijsand@peculiar/asn1-schemacheckinstanceof asn1js.Sequenceand similar, so objects from asn1js 4 fail those checks in a library that still depends on asn1js 3. Upgrade them together. - New
RangeErrors:new Integer({ value })and thevalueDecsetter reject non-integer numbers (v3 truncated1.5to1and encodedNaNas empty). Encoding aUTCTimewith a year outside 1950–2049 throws, includingnew UTCTime({ valueDate }); v3 wrapped 2050 to 1950. UseGeneralizedTimefor those dates. - Encodings that differ from v3:
Integer.fromBigIntencodes negative values correctly (v3:-32767n→0x81,-128n→0xff80).UniversalStringwrites characters outside the BMP as one UCS-4 code point (U+1F600→0001f600, v3 wrote a surrogate pair; v3 output still decodes). OID arcs and tag numbers from 2^49 to 2^53 now encode (v3 produced an empty value). - Decoding: a
BMPStringwith an odd length or aUniversalStringwhose length isn't a multiple of 4 returns an error (offset: -1) instead of throwing.UniversalStringlone surrogates and code points above U+10FFFF become U+FFFD with a warning. OID arcs and tag numbers above 2^53 stay hex-only and re-encode unchanged. "Needlessly long encoded length" now checks the first length octet, so lengths such as83 00 00 07get the warning.
ASN1js is the first library for BER encoding/decoding in JavaScript designed for browser use. BER is the basic encoding rules for ASN.1 that all others are based on, DER is the encoding rules used by PKI applications - it is a subset of BER. The ASN1js library was tested against freely available ASN.1:2008 test suite, with some limitations related to JavaScript language.
- Based on latest features of JavaScript language from ES2015 standard;
- ASN1js is a "base layer" for full-featured JS library PKIjs, which is using Web Cryptography API and has all classes, necessary to work with PKI-related data;
- Fully object-oriented library. Inheritance is used everywhere inside the lib;
- Working with HTML5 data objects (ArrayBuffer, Uint8Array etc.);
- Working with all ASN.1:2008 types;
- Working with BER encoded data;
- All types inside the library constantly stores information about all ASN.1 sub blocks (tag block, length block or value block);
- User may have access to any byte inside any ASN.1 sub-block;
- Any sub-block may have unlimited length, as it described in ASN.1 standard (even "tag block");
- Ability to work with ASN.1 string data types (including all "international" strings like UniversalString, BMPString, UTF8String) by passing native JavaScript strings into constructors. And vice versa - all initially parsed data of ASN.1 string types right after decoding automatically converts into native JavaScript strings;
- Same with ASN.1 date-time types: for major types like UTCTime and GeneralizedTime there are automatic conversion between "JS date type - ASN.1 date-time type" + vice versa;
- Same with ASN.1 OBJECT-IDENTIFIER (OID) data-type: you can initialize OID by JavaScript string and can get its string representation by calling
oid.getValue(); - Working with "easy-to-understand" ASN.1 schemas (pre-defined or built by user);
- Has special types to work with ASN.1 schemas:
- Any
- Choice
- Repeated
- User can name any block inside ASN.1 schema and easily get information by name;
- Ability to parse internal data inside primitively encoded data types and automatically validate it against special schema;
- All types inside library are dynamic;
- All types can be initialized in static or dynamic ways.
- ASN1js fully tested against ASN.1:2008 TestSuite.
Runnable examples are on the website:
- Basics: decode BER and DER, encode to DER, convert to JavaScript values, explicit and implicit tags
- Schemas: validate against a schema, CHOICE and SEQUENCE OF, structures inside an OCTET STRING
- Real-world data: read an X.509 certificate, read a public key, parse untrusted input
For complete PKI structures such as certificates, CMS, and PKCS#10 requests, see PKIjs, which is built on ASN1js.
ObjectIdentifier and RelativeObjectIdentifier preserve large decimal components exactly, including UUID-based OIDs such as 2.25.329800735698586629295641978511506172918. getValue(), ASCII output, and JSON values use decimal notation even when a component is stored internally as hex-only.
String values must contain complete non-negative decimal components. Absolute OIDs need at least two components: the first is 0, 1, or 2, and the second is at most 39 when the first is 0 or 1. Leading zeros, surrounding whitespace in each component, a leading +, and negative zero are normalized. Partial numbers, hexadecimal prefixes, and exponent notation are rejected.
By default, invalid strings clear the value and set both error and valueBlock.error without throwing. They no longer encode as another OID or as a valid prefix. For compatibility, toBER() still returns an empty OID (0600 or 0d00) on failure; check the OID's diagnostics before using the output, including when it is nested in a constructed value. Parent blocks do not propagate the child's error. A successful setValue() clears previous value errors. Constructors with an omitted value, undefined, null, or "" create empty placeholders without errors for schema declarations. An explicit setValue("") still records a validation error.
Pass strict: true to make invalid construction, value assignment, and encoding throw an Error. The same decimal input rules and normalizations apply in both modes. An explicit value: "" is invalid in a strict constructor; omit the value to create a strict schema placeholder. RelativeObjectIdentifier supports the same option.
const oid = new asn1js.ObjectIdentifier({
value: "1.2.840.113549",
strict: true,
});
oid.setValue("1.40"); // Throws; the object is left invalid with diagnostics.Strict encoding checks the current SID values on every toBER() call, including toBER(true), so later mutations cannot silently produce an empty value. After a failed assignment or encoding, use a successful setValue() or decode a complete replacement value to recover; changing the SID array or turning strict mode off does not clear recorded errors. Constructors without a value remain valid strict schema placeholders, but encoding an empty placeholder throws. toString("hex") also encodes the value and throws for invalid strict OIDs. isEqual() can throw when it needs to encode an invalid strict OID for comparison.
OID instance and value-block fromBER() calls replace previous SID values, lengths, and value diagnostics. Failed decoding discards any parsed prefix and reports the error without throwing. The instance method expects content octets and a prepared length block; use the top-level fromBER() function to decode a complete BER encoding.
You can also set oid.strict = true on an existing or decoded OID. Changing the flag does not validate or modify its value immediately. The flag defaults to false, is not serialized in BER or JSON, and does not change the permissive behavior of fromBER().
An error from a strict OID aborts the normal encoding of its enclosing Sequence, Set, or Constructed value. Enable strict mode on each OID that needs this behavior. If encoding throws with an explicit ViewWriter, discard that writer: earlier writes are retained and are not rolled back. Strict mode checks OID values; it does not validate arbitrary changes to tag/length blocks or custom serializer implementations.
fromBER() accepts optional parser resource limits for untrusted ASN.1 input.
const asn1 = asn1js.fromBER(inputBuffer, {
maxDepth: 100,
maxNodes: 10000,
maxContentLength: 16 * 1024 * 1024,
});When any limit is exceeded the parser returns a normal FromBerResult error instead of exhausting the JavaScript stack or continuing to parse excessive input. See the untrusted input example.
In the default BER mode, primitive OCTET STRING values and primitive BIT STRING values with zero unused bits are also checked for a complete embedded ASN.1 value. Set parseEmbedded: false to keep those values as raw bytes without that heuristic interpretation; constructed children continue to be parsed normally.
Input is copied by default. Set copyInput: false to retain a normalized view over the exact input range without copying. The caller must keep the backing storage unchanged and must not detach it while the parsed tree is in use: mutations are visible through parsed byte views and can make them inconsistent with decoded fields. The entire backing buffer remains retained. This option provides no protection against shared-memory races.
For performance-sensitive callers that can meet these storage requirements, the following example explicitly opts out of copying the input. It also independently disables embedded-value detection with parseEmbedded: false; that option does not change input ownership.
const asn1 = asn1js.fromBER(inputBuffer, {
maxDepth: 100,
maxNodes: 10000,
maxContentLength: 16 * 1024 * 1024,
parseEmbedded: false,
copyInput: false,
});Use fromDER() to parse exactly one DER element, or pass encodingRules: "DER" to
fromBER() or verifySchema(). BER remains the default, and fromBER() still
parses the first element unless full input consumption is requested. See the
compatibility notes below for changes that also affect BER callers.
import { fromBER, fromDER, verifySchema } from "asn1js";
const parsed = fromDER(inputBuffer, { maxNodes: 10000 });
if (parsed.offset === -1) {
console.error(parsed.result.error, parsed.diagnostic);
}
// Equivalent encoding checks:
const strict = fromBER(inputBuffer, { encodingRules: "DER" });
const checked = verifySchema(inputBuffer, schema, { encodingRules: "DER" });
// BER encodings, including indefinite lengths, with no trailing data:
const completeBer = fromBER(inputBuffer, { requireFullInput: true });| Options | Behavior |
|---|---|
BER defaults, or requireFullInput: false |
Parse the first element and return its end offset. |
BER with requireFullInput: true |
Require exactly one complete BER element. |
encodingRules: "DER" |
Require exactly one element and validate supported DER rules. |
DER with requireFullInput: false |
Throw TypeError for incompatible options. |
FromBerOptions remains an extensible interface. EncodingRules is "BER" | "DER".
FromDerOptions is Omit<FromBerOptions, "encodingRules" | "requireFullInput">, since
fromDER() always selects DER and requires full input consumption. Both APIs accept
ArrayBuffer and buffer views; offsets are relative to the exact supplied view.
Direct calls to a block's fromBER() method without a parser context keep BER behavior.
Successful DER parsing checks the input bytes at the time of the call: one TLV,
minimal identifiers and definite lengths, required UNIVERSAL forms, supported
primitive contents, and recursively parsed constructed children. It does not give
an enduring certificate of validity to a mutable tree or backing buffer. The
copyInput option and resource limits work as described above.
| UNIVERSAL types | DER validation |
|---|---|
| BOOLEAN, INTEGER, ENUMERATED, BIT STRING, OCTET STRING, NULL, OBJECT IDENTIFIER, RELATIVE-OID | Canonical form and contents, including minimal integers/OID groups and zero BIT STRING padding. |
| UTF8String, NumericString, PrintableString, IA5String, VisibleString, BMPString, UniversalString | Primitive form, valid encoding and character repertoire. BMPString and UniversalString reject surrogates and values outside Unicode. |
| UTCTime, GeneralizedTime | Complete UTC form with seconds and uppercase Z, valid calendar/clock fields, canonical fractional seconds. |
| SEQUENCE, SET | Constructed form and recursively validated children. Ordering needs schema information. |
| TeletexString, VideotexString, GraphicString, GeneralString | Primitive form only; ISO 2022 contents remain opaque, allowing legacy T61 certificate names. |
| ObjectDescriptor (7), EXTERNAL (8), REAL (9), EMBEDDED PDV (11), TIME (14), CHARACTER STRING (29), DATE/TIME-OF-DAY/DATE-TIME/DURATION (31–34), unknown types 35–36 | UNSUPPORTED_DER_TYPE: the core cannot validate the type. |
| EOC (0), reserved 15 and tags 37 or higher | Rejected with UNEXPECTED_EOC or INVALID_FORM. |
Time validation examines the original octets, preserving arbitrary fractional
precision. GeneralizedTime fractions use . and omit all trailing zeros; a zero
fraction is omitted entirely. UTCTime does not allow fractions. Converting the
result with toDate() can lose precision. GeneralizedTime permits a leap second
only at 23:59 on the final day of a UTC month; UTCTime seconds are restricted to
00–59. No historical leap-second table is consulted.
JavaScript Date cannot represent a leap second: toDate() normalizes it to the
following minute. This does not mutate the parsed fields or original bytes;
toBER() still preserves the original encoding.
APPLICATION, CONTEXT-SPECIFIC, and PRIVATE elements receive the same header checks, and their constructed children are validated recursively. Primitive contents stay opaque until a schema resolves their type. DER validation does not authenticate certificate signatures or verify application-level constraints.
Integration tests validate and round-trip every root certificate bundled with the Node.js test runtime, alongside a generated legacy T61 certificate and a CRL with 5,000 revoked entries.
BER keeps prefix parsing for both the outer element and primitiveSchema contents.
For example, 04 05 02 01 01 de ad still matches an OCTET STRING with an INTEGER
primitiveSchema through verifySchema() or compareSchema(). Pass
requireFullInput: true to verifySchema() to require complete outer and embedded
values, or select DER, which always requires full consumption.
verifySchema() keeps borrowing the supplied input range by default. Set
copyInput: true to copy it; fromBER() and fromDER() still copy by default.
The input ownership and mutation requirements described
under Parsing Untrusted Input apply to the returned
tree and named schema captures: borrowed byte views reflect later mutations,
decoded fields may then disagree with those bytes, and the entire backing buffer
stays retained.
DER PrintableString validation enforces the exact X.680 repertoire: letters
A–Z and a–z, digits 0–9, space, and ' ( ) + , - . / : = ?.
It rejects *, &, and @, so a certificate with a wildcard CN encoded as
PrintableString can fail strict parsing. For new values, use Utf8String for
these characters, or IA5String for DNS names where the schema allows it.
DER checks are not relaxed for legacy certificates; changing the tag in an
existing signed certificate is not a valid repair.
BER UTCTime accepts optional seconds and either Z or a signed hhmm offset
(YYMMDDhhmm[ss](Z|+hhmm|-hhmm)). DER still requires YYMMDDHHMMSSZ.
The new 10-digit Z and signed-offset forms validate their calendar and clock
fields before UTC normalization. The original 12-digit Z form keeps its legacy
BER calendar/clock, lowercase z, and unanchored matching tolerance.
BER keeps the legacy UTCTime conversion-error behavior: a decoded field can carry
an error while the parser returns its end offset and continues to later siblings.
Malformed GeneralizedTime conversions keep throwing in BER. DER rejects malformed
times with a validation failure before conversion.
An offset can normalize a BER UTCTime into UTC year 1949 or 2050. The parsed fields
and toDate() reflect that UTC time, and toBER() preserves the original bytes.
toBuffer() produces a UTC representation and throws when that year is outside
1950–2049; use GeneralizedTime when creating a value outside that UTC year range.
An input validation failure returns offset: -1, sets result.error, and provides
diagnostic when a structured code is available. Its stable contract is code,
offset, and depth: offset identifies the start of the failing TLV, and root
depth is zero. For TRAILING_DATA, offset identifies the first extra byte.
byteOffset optionally locates an exact byte. Message text may change. Resource
limit and ordinary structural decoder failures can have no diagnostic.
verifySchema() carries the same diagnostic into its failed result, including
failures in mandatory primitiveSchema parsing.
When all Choice alternatives fail, the result keeps the Choice's name and the
Wrong values for Choice type error. The diagnostic from the last alternative
that supplied one is retained separately. With a shared resource budget (DER or
explicit parser limits), resource-limit failures remain fatal and are returned
directly instead of being wrapped as a Choice mismatch.
The exported DerViolationCode values are:
- Document/header:
TRAILING_DATA,INDEFINITE_LENGTH,NON_MINIMAL_LENGTH,NON_MINIMAL_TAG. - Form/support:
INVALID_FORM,UNEXPECTED_EOC,UNSUPPORTED_DER_TYPE. - Primitive contents:
EMPTY_VALUE,NON_MINIMAL_INTEGER,INVALID_BOOLEAN,INVALID_NULL,BIT_STRING_UNUSED_BITS,BIT_STRING_PADDING,INVALID_OID,INVALID_STRING,INVALID_TIME. - Schema ordering helpers:
SET_ORDER,SET_OF_ORDER.
UNSUPPORTED_DER_TYPE means validation is unavailable; it does not assert that the
encoding is invalid. DerIssue describes a local helper result with optional
contentOffset or elementIndex; ParseDiagnostic adds document position and depth.
DER defaults to parseEmbedded: false. With explicit parseEmbedded: true, the
OCTET STRING and BIT STRING heuristic uses a separate, monotonic budget of
maxNodes, alongside the required parse's maxNodes budget. Failed attempts still
consume heuristic work, giving a combined bound of twice maxNodes. Exhausting
that budget stops further attempts and retains raw contents without failing the
required parse. A failed attempt cannot replace the required parse's diagnostic.
Successful heuristic valueBlock.value children passed the DER checks supported by
the core; schema-dependent constraints are still outside that guarantee.
A schema's primitiveSchema requests parsing of its contents with the selected
encoding rules. Under DER it uses the same resource context, requires full
consumption, and reports DER violations. For example, an OCTET STRING containing
02 02 00 01 fails with NON_MINIMAL_INTEGER when its required primitiveSchema
is INTEGER. A failed Choice alternative or optional field does not prevent a
different schema alternative from matching; failures of a shared resource budget
remain fatal.
Legacy BER gives each primitiveSchema parse an independent default resource
budget. Passing maxNodes, maxDepth, or maxContentLength explicitly to
verifySchema() instead shares the resource context across the outer parse and
embedded schema attempts, including failed alternatives. DER always shares that
context. requireFullInput: true alone changes completeness checks without
changing the legacy BER resource-budget scope.
In legacy BER, a failed independent embedded parse can still fall back to another
Choice alternative, including after that embedded parse reaches its own limit.
The core cannot infer SET versus SET OF ordering, omitted DEFAULT values, the last
significant bit of a NamedBitList, or the underlying type of IMPLICIT contents.
Schema-aware consumers can use the pure der helpers on original bytes:
import { der } from "asn1js";
// [0] IMPLICIT INTEGER: validate contents before rebuilding the typed object.
const issue = der.checkPrimitiveEncoding(2, block.idBlock.isConstructed, block.valueBlock.valueHexView);
const setOfIssue = der.checkSetOfOrder(children.map((child) => child.valueBeforeDecodeView));
const setIssue = der.checkSetOrder(identifierOctets);
const comparison = der.compareSetOfElements(firstEncoding, secondEncoding);checkPrimitiveEncoding() returns undefined for supported valid contents or a
DerIssue. SEQUENCE, SET, and unsupported types return UNSUPPORTED_DER_TYPE.
checkSetOrder() compares the actual encoded tag class and numeric tag, ignoring
the constructed flag and supporting arbitrarily large tags. For an untagged CHOICE,
use the selected alternative's identifier. Its identifiers must already be complete
and minimally encoded. checkSetOfOrder() and compareSetOfElements() compare full,
already validated encodings as octet strings with conceptual trailing zero padding
(X.690 11.6). Ordering alone does not establish element validity.
DEFAULT omission requires comparing ASN.1 values rather than arbitrary TLVs:
80 01 00 ([0] IMPLICIT INTEGER zero) and 02 01 00 represent the same value despite
different bytes. Validation of an existing object tree cannot establish the original
encoding; strict schema parsing starts from the original bytes within one call.
- C++ ASN1:2008 BER coder/decoder - the "father" of ASN1js project;
- Freely available ASN.1:2008 test suite - the suite which can help you to validate (and better understand) any ASN.1 coder/decoder;
- NPM package for ASN.1:2008 test suite
There are several commercial products, enterprise solutions as well as open source project based on versions of ASN1js. You should, however, do your own code and security review before using any open source library in a production application to ensure it will meet your needs.
See CONTRIBUTING.md for development setup, commit conventions and the release flow.
asn1js is released under the BSD 3-Clause License.