asn1js
v4.0.0
Published
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
Downloads
90,943,510
Readme
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.
Install
npm install asn1jsBreaking Changes In v4
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 exported API is unchanged, 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.
Important Information for ASN1.js V1 Users
ASN1.js V2 (ES2015 version) is incompatible with ASN1.js V1 code.
Introduction
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.
Features of the library
- 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 using 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 date 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 string representation via calling "oid.valueBlock.toString()";
- 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 a 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.
Examples
How to create new ASN. structures
var sequence = new asn1js.Sequence();
sequence.valueBlock.value.push(new asn1js.Integer({ value: 1 }));
var sequence_buffer = sequence.toBER(false); // Encode current sequence to BER (in ArrayBuffer)
var current_size = sequence_buffer.byteLength;
var integer_data = new ArrayBuffer(8);
var integer_view = new Uint8Array(integer_data);
integer_view[0] = 0x01;
integer_view[1] = 0x01;
integer_view[2] = 0x01;
integer_view[3] = 0x01;
integer_view[4] = 0x01;
integer_view[5] = 0x01;
integer_view[6] = 0x01;
integer_view[7] = 0x01;
sequence.valueBlock.value.push(
new asn1js.Integer({
isHexOnly: true,
valueHex: integer_data,
}),
); // Put too long for decoding Integer value
sequence_buffer = sequence.toBER();
current_size = sequence_buffer.byteLength;How to create new ASN.1 structures by calling constructors with parameters
var sequence2 = new asn1js.Sequence({
value: [
new asn1js.Integer({ value: 1 }),
new asn1js.Integer({
isHexOnly: true,
valueHex: integer_data,
}),
],
});How to validate ASN.1 against pre-defined schema
var asn1_schema = new asn1js.Sequence({
name: "block1",
value: [
new asn1js.Null({
name: "block2",
}),
new asn1js.Integer({
name: "block3",
optional: true, // This block is absent inside data, but it's "optional". Hence verification against the schema will be passed.
}),
],
});
var variant1 = asn1js.verifySchema(encoded_sequence, asn1_schema); // Verify schema together with decoding of raw data
var variant1_verified = variant1.verified;
var variant1_result = variant1.result; // Verified decoded data with all block names insideHow to use "internal schemas" for primitively encoded data types
var primitive_octetstring = new asn1js.OctetString({ valueHex: encoded_sequence }); // Create a primitively encoded OctetString where internal data is an encoded Sequence
var asn1_schema_internal = new asn1js.OctetString({
name: "outer_block",
primitiveSchema: new asn1js.Sequence({
name: "block1",
value: [
new asn1js.Null({
name: "block2",
}),
],
}),
});
var variant6 = asn1js.compareSchema(primitive_octetstring, primitive_octetstring, asn1_schema_internal);
var variant6_verified = variant4.verified;
var variant6_block1_tag_num = variant6.result.block1.idBlock.tagNumber;
var variant6_block2_tag_num = variant6.result.block2.idBlock.tagNumber;More examples could be found in "examples" directory or inside PKIjs library.
Parsing Untrusted Input
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.
By default, 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,
});Related source code
- 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
Suitability
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 utilization in a production application before utilizing any open source library to ensure it will meet your needs.
Contributing
See CONTRIBUTING.md for development setup, commit conventions and the release flow.
License
Copyright (c) 2014, GMO GlobalSign Copyright (c) 2015-2022, Peculiar Ventures All rights reserved.
Author 2014-2018, Yury Strozhevsky.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
