···1+# ChangeLog
2+3+## 2.1.1 - 2025-10-24
4+5+### Changed
6+7+- update dev dependencies
8+- fix test suite that was reporting no error with empty responses
9+10+### Added
11+12+- add content length check for BOOLEAN, INTEGER, OID ([GitHub #104](https://github.com/lapo-luchini/asn1js/pull/104))
13+14+## 2.1.0 - 2025-08-03
15+16+### Changed
17+18+- when fields are CHOICEs now both the field name and the choice name are shown (fixes [GitHub #102](https://github.com/lapo-luchini/asn1js/issues/102))
19+- upgrade minimum NodeJS version supported from 12.20.0 to 14.6.0 due to usage of ?. and ?? operators in defs.js (ECMAScript 2020); older code is still linted against ECMAScript 2015 for now
20+21+### Added
22+23+- add tests to check expected decoding
24+25+## 2.0.6 - 2025-07-29
26+27+### Added
28+29+- add proper support for standard Base64 (we previously only supported Base64url) (fixes [GitHub #99](https://github.com/lapo-luchini/asn1js/pull/99))
30+- improve test harness
31+32+## 2.0.5 - 2025-04-12
33+34+### Added
35+36+- add `index-local.html` for local `file://` usage without needing a web server
37+- add definitions support for `LDAPMessage`
38+- #TODO continue producing old ChangeLog entries
+1-1
LICENSE
···1ISC License
23-Copyright (c) 2008-2024 Lapo Luchini <lapo@lapo.it>
45Permission to use, copy, modify, and/or distribute this software for any
6purpose with or without fee is hereby granted, provided that the above
···1ISC License
23+Copyright (c) 2008-2025 Lapo Luchini <lapo@lapo.it>
45Permission to use, copy, modify, and/or distribute this software for any
6purpose with or without fee is hereby granted, provided that the above
+48-13
README.md
···34asn1js is a JavaScript generic ASN.1 parser/decoder that can decode any valid ASN.1 DER or BER structures.
56-An example page that can decode Base64-encoded (raw base64, PEM armoring and `begin-base64` are recognized) or Hex-encoded (or local files with some browsers) is included and can be used both [online on the official website](https://lapo.it/asn1js/) or [offline (ZIP file)](https://lapo.it/asn1js/asn1js.zip).
78-Usage with `npm` / `yarn`
9--------------------------
1011This package can be installed with either npm or yarn via the following commands:
12···17yarn add @lapo/asn1js
18```
1920-Assuming a standard javascript bundler is setup you can import it like so:
2122```js
23-import ASN1 from '@lapo/asn1js';
24```
2526A submodule of this package can also be imported:
2728```js
29-import Hex from '@lapo/asn1js/hex';
00000000030```
3132-Unfortunately until [`require(esm)` gets released](https://joyeecheung.github.io/blog/2024/03/18/require-esm-in-node-js/) it is necessary to use async `import()` when used from CommonJS (legacy NodeJS) code.
00000000003334Usage on the web
35--------------------
···3839```html
40<script>
41-import { ASN1} from 'https://unpkg.com/@lapo/asn1js@2.0.0/asn1.js';
42import { Hex } from 'https://unpkg.com/@lapo/asn1js@2.0.0/hex.js';
4344document.body.innerText = ASN1.decode(Hex.decode('06032B6570')).content();
45</script>
46```
470000000000000048ISC license
49-----------
5051-ASN.1 JavaScript decoder Copyright (c) 2008-2024 Lapo Luchini <lapo@lapo.it>
5253Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
54···62- extended tag support added by [Pรฉter Budai](https://www.peterbudai.eu/)
63- patches by [Gergely Nagy](https://github.com/ngg)
64- Relative OID support added by [Mistial Developer](https://github.com/mistial-dev)
65-- dark mode support added by [Oliver Burgmaier](https://github.com/olibu/)
66- patches by [Nicolai Sรธborg](https://github.com/NicolaiSoeborg)
6768links
69-----
7071-- [official website](https://lapo.it/asn1js/)
72-- [dedicated domain](https://asn1js.eu/)
73-- [InDefero tracker](http://idf.lapo.it/p/asn1js/)
074- [GitHub mirror](https://github.com/lapo-luchini/asn1js)
075- [Ohloh code stats](https://www.openhub.net/p/asn1js)
···34asn1js is a JavaScript generic ASN.1 parser/decoder that can decode any valid ASN.1 DER or BER structures.
56+An example page that can decode Base64-encoded (raw base64, PEM armoring and `begin-base64` are recognized) or Hex-encoded (or local files with some browsers) is included and can be used both [online on the official website](https://asn1js.eu/) or [offline (ZIP file)](https://lapo.it/asn1js/asn1js.zip) by opening `index-local.html`.
78+Usage with `nodejs`
9+-------------------
1011This package can be installed with either npm or yarn via the following commands:
12···17yarn add @lapo/asn1js
18```
1920+You can import the classes like this:
2122```js
23+import { ASN1 } from '@lapo/asn1js';
24```
2526A submodule of this package can also be imported:
2728```js
29+import { Hex } from '@lapo/asn1js/hex.js';
30+```
31+32+If your code is still not using ES6 Modules (and is using CommonJS) you can `require` it normally [since NodeJS 22](https://joyeecheung.github.io/blog/2024/03/18/require-esm-in-node-js/) (with parameter `--experimental-require-module`):
33+34+```js
35+const
36+ { ASN1 } = require('@lapo/asn1js'),
37+ { Hex } = require('@lapo/asn1js/hex.js');
38+console.log(ASN1.decode(Hex.decode('06032B6570')).content());
39```
4041+On older NodeJS you instead need to use async `import`:
42+43+```js
44+async function main() {
45+ const
46+ { ASN1 } = await import('@lapo/asn1js'),
47+ { Hex } = await import('@lapo/asn1js/hex.js');
48+ console.log(ASN1.decode(Hex.decode('06032B6570')).content());
49+}
50+main();
51+```
5253Usage on the web
54--------------------
···5758```html
59<script>
60+import { ASN1 } from 'https://unpkg.com/@lapo/asn1js@2.0.0/asn1.js';
61import { Hex } from 'https://unpkg.com/@lapo/asn1js@2.0.0/hex.js';
6263document.body.innerText = ASN1.decode(Hex.decode('06032B6570')).content();
64</script>
65```
6667+Local usage
68+--------------------
69+70+Since unfortunately ESM modules are not working on `file:` protocol due to [CORS issues](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#other_differences_between_modules_and_standard_scripts), there is a bundled [single-file version working locally](https://asn1js.eu/index-local.html). It doesn't work online (due to [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) restrictions about inline content) but can be saved locally and opened in a browser.
71+72+Usage from CLI
73+--------------------
74+75+You can dump an ASN.1 structure from the command line using the following command (no need to even install it):
76+77+```sh
78+npx @lapo/asn1js ed25519.cer
79+```
80+81ISC license
82-----------
8384+ASN.1 JavaScript decoder Copyright (c) 2008-2025 Lapo Luchini <lapo@lapo.it>
8586Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
87···95- extended tag support added by [Pรฉter Budai](https://www.peterbudai.eu/)
96- patches by [Gergely Nagy](https://github.com/ngg)
97- Relative OID support added by [Mistial Developer](https://github.com/mistial-dev)
98+- dark mode and other UI improvements by [Oliver Burgmaier](https://github.com/olibu/)
99- patches by [Nicolai Sรธborg](https://github.com/NicolaiSoeborg)
100101links
102-----
103104+- [official website](https://asn1js.eu/)
105+- [alternate website](https://lapo.it/asn1js/)
106+- [single-file version working locally](https://asn1js.eu/index-local.html) (just save this link)
107+- [InDefero tracker](http://idf.lapo.it/p/asn1js/) (currently offline)
108- [GitHub mirror](https://github.com/lapo-luchini/asn1js)
109+- [ChangeLog on GitHub](https://github.com/lapo-luchini/asn1js/blob/trunk/CHANGELOG.md)
110- [Ohloh code stats](https://www.openhub.net/p/asn1js)
+343-89
asn1.js
···1// ASN.1 JavaScript decoder
2-// Copyright (c) 2008-2024 Lapo Luchini <lapo@lapo.it>
34// Permission to use, copy, modify, and/or distribute this software for any
5// purpose with or without fee is hereby granted, provided that the above
6// copyright notice and this permission notice appear in all copies.
7-//
8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
···13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1516-import { Int10 } from './int10.js';
17import { oids } from './oids.js';
1819const
···21 reTimeS = /^(\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|(-(?:0\d|1[0-2])|[+](?:0\d|1[0-4]))([0-5]\d)?)?$/,
22 reTimeL = /^(\d\d\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|(-(?:0\d|1[0-2])|[+](?:0\d|1[0-4]))([0-5]\d)?)?$/,
23 hexDigits = '0123456789ABCDEF',
24- b64Safe = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
025 tableT61 = [
26 ['', ''],
27 ['AEIOUaeiou', 'รรรรรร รจรฌรฒรน'], // Grave
···41 ['CDELNRSTZcdelnrstz', 'ฤฤฤฤฝลลล ลคลฝฤฤฤฤพลลลกลฅลพ'], // Caron
42 ];
4300000044function stringCut(str, len) {
45 if (str.length > len)
46 str = str.substring(0, len) + ellipsis;
47 return str;
48}
490000050function checkPrintable(s) {
51 let i, v;
52 for (i = 0; i < s.length; ++i) {
···56 }
57}
5859-class Stream {
0000600000061 constructor(enc, pos) {
62 if (enc instanceof Stream) {
63 this.enc = enc.enc;
64 this.pos = enc.pos;
65 } else {
66- // enc should be an array or a binary string
67 this.enc = enc;
68 this.pos = pos;
69 }
00000000070 }
00000071 get(pos) {
72 if (pos === undefined)
73 pos = this.pos++;
74 if (pos >= this.enc.length)
75- throw 'Requesting byte offset ' + pos + ' on a stream of length ' + this.enc.length;
76- return (typeof this.enc == 'string') ? this.enc.charCodeAt(pos) : this.enc[pos];
77 }
78- hexByte(b) {
00000079 return hexDigits.charAt((b >> 4) & 0xF) + hexDigits.charAt(b & 0xF);
80 }
81- hexDump(start, end, raw) {
0000000082 let s = '';
83 for (let i = start; i < end; ++i) {
84- s += this.hexByte(this.get(i));
85- if (raw !== true)
0086 switch (i & 0xF) {
87 case 0x7: s += ' '; break;
88 case 0xF: s += '\n'; break;
···91 }
92 return s;
93 }
94- b64Dump(start, end) {
95- let extra = (end - start) % 3,
96- s = '',
00000000097 i, c;
98 for (i = start; i + 2 < end; i += 3) {
99 c = this.get(i) << 16 | this.get(i + 1) << 8 | this.get(i + 2);
100- s += b64Safe.charAt(c >> 18 & 0x3F);
101- s += b64Safe.charAt(c >> 12 & 0x3F);
102- s += b64Safe.charAt(c >> 6 & 0x3F);
103- s += b64Safe.charAt(c & 0x3F);
104 }
105 if (extra > 0) {
106 c = this.get(i) << 16;
107 if (extra > 1) c |= this.get(i + 1) << 8;
108- s += b64Safe.charAt(c >> 18 & 0x3F);
109- s += b64Safe.charAt(c >> 12 & 0x3F);
110- if (extra == 2) s += b64Safe.charAt(c >> 6 & 0x3F);
0111 }
112 return s;
113 }
0000000114 isASCII(start, end) {
115 for (let i = start; i < end; ++i) {
116 let c = this.get(i);
···119 }
120 return true;
121 }
00000000122 parseStringISO(start, end, maxLength) {
123 let s = '';
124 for (let i = start; i < end; ++i)
125 s += String.fromCharCode(this.get(i));
126 return { size: s.length, str: stringCut(s, maxLength) };
127 }
00000000128 parseStringT61(start, end, maxLength) {
129 // warning: this code is not very well tested so far
130 function merge(c, d) {
131- let t = tableT61[c - 0xC0];
132- let i = t[0].indexOf(String.fromCharCode(d));
133 return (i < 0) ? '\0' : t[1].charAt(i);
134 }
135 let s = '', c;
···146 }
147 return { size: s.length, str: stringCut(s, maxLength) };
148 }
00000000149 parseStringUTF(start, end, maxLength) {
00000150 function ex(c) { // must be 10xxxxxx
151 if ((c < 0x80) || (c >= 0xC0))
152 throw new Error('Invalid UTF-8 continuation byte: ' + c);
153 return (c & 0x3F);
154 }
00000155 function surrogate(cp) {
156 if (cp < 0x10000)
157 throw new Error('UTF-8 overlong encoding, codepoint encoded in 4 bytes: ' + cp);
···161 }
162 let s = '';
163 for (let i = start; i < end; ) {
164- let c = this.get(i++);
165 if (c < 0x80) // 0xxxxxxx (7 bit)
166 s += String.fromCharCode(c);
167 else if (c < 0xC0)
···177 }
178 return { size: s.length, str: stringCut(s, maxLength) };
179 }
00000000180 parseStringBMP(start, end, maxLength) {
181 let s = '', hi, lo;
182 for (let i = start; i < end; ) {
···186 }
187 return { size: s.length, str: stringCut(s, maxLength) };
188 }
00000000189 parseTime(start, end, shortYear) {
190 let s = this.parseStringISO(start, end).str,
191 m = (shortYear ? reTimeS : reTimeL).exec(s);
192 if (!m)
193- return 'Unrecognized time: ' + s;
194 if (shortYear) {
195 // to avoid querying the timer, use the fixed range [1970, 2069]
196 // it will conform with ITU X.400 [-10, +40] sliding window until 2030
···213 }
214 return s;
215 }
0000000216 parseInteger(start, end) {
217 let v = this.get(start),
218- neg = (v > 127),
219- pad = neg ? 255 : 0,
220- len,
221 s = '';
00222 // skip unuseful bits (not allowed in DER)
223 while (v == pad && ++start < end)
224 v = this.get(start);
225- len = end - start;
226 if (len === 0)
227 return neg ? '-1' : '0';
228 // show bit length of huge integers
229 if (len > 4) {
230- s = v;
231- len <<= 3;
232- while (((s ^ pad) & 0x80) == 0) {
233- s <<= 1;
234- --len;
235 }
236- s = '(' + len + ' bit)\n';
237 }
238 // decode the integer
239 if (neg) v = v - 256;
240- let n = new Int10(v);
241 for (let i = start + 1; i < end; ++i)
242- n.mulAdd(256, this.get(i));
243- return s + n.toString();
244 }
00000000245 parseBitString(start, end, maxLength) {
246- let unusedBits = this.get(start);
247 if (unusedBits > 7)
248- throw 'Invalid BitString with unusedBits=' + unusedBits;
249- let lenBit = ((end - start - 1) << 3) - unusedBits,
250- s = '';
251 for (let i = start + 1; i < end; ++i) {
252 let b = this.get(i),
253 skip = (i == end - 1) ? unusedBits : 0;
···258 }
259 return { size: lenBit, str: s };
260 }
00000000261 parseOctetString(start, end, maxLength) {
262- let len = end - start,
263- s;
264 try {
265- s = this.parseStringUTF(start, end, maxLength);
266 checkPrintable(s.str);
267 return { size: end - start, str: s.str };
268- } catch (e) {
269- // ignore
270 }
0271 maxLength /= 2; // we work in bytes
272 if (len > maxLength)
273 end = start + maxLength;
274- s = '';
275 for (let i = start; i < end; ++i)
276- s += this.hexByte(this.get(i));
277 if (len > maxLength)
278 s += ellipsis;
279 return { size: len, str: s };
280 }
000000000281 parseOID(start, end, maxLength, isRelative) {
282 let s = '',
283- n = new Int10(),
284 bits = 0;
285 for (let i = start; i < end; ++i) {
286 let v = this.get(i);
287- n.mulAdd(128, v & 0x7F);
0288 bits += 7;
0289 if (!(v & 0x80)) { // finished
0290 if (s === '') {
291- n = n.simplify();
292 if (isRelative) {
293- s = (n instanceof Int10) ? n.toString() : '' + n;
294- } else if (n instanceof Int10) {
295- n.sub(80);
296- s = '2.' + n.toString();
297 } else {
298- let m = n < 80 ? n < 40 ? 0 : 1 : 2;
299- s = m + '.' + (n - m * 40);
300 }
301 } else
302- s += '.' + n.toString();
303 if (s.length > maxLength)
304 return stringCut(s, maxLength);
305- n = new Int10();
306 bits = 0;
307 }
308 }
309 if (bits > 0)
310 s += '.incomplete';
0311 if (typeof oids === 'object' && !isRelative) {
312 let oid = oids[s];
313 if (oid) {
···318 }
319 return s;
320 }
00000000321 parseRelativeOID(start, end, maxLength) {
322 return this.parseOID(start, end, maxLength, true);
323 }
···350 this.tagConstructed = ((buf & 0x20) !== 0);
351 this.tagNumber = buf & 0x1F;
352 if (this.tagNumber == 0x1F) { // long tag
353- let n = new Int10();
354 do {
355 buf = stream.get();
356- n.mulAdd(128, buf & 0x7F);
357 } while (buf & 0x80);
358- this.tagNumber = n.simplify();
359 }
360 }
361 isUniversal() {
···366 }
367}
3680000369export class ASN1 {
000000000370 constructor(stream, header, length, tag, tagLen, sub) {
371- if (!(tag instanceof ASN1Tag)) throw 'Invalid tag value.';
372 this.stream = stream;
373 this.header = header;
374 this.length = length;
···376 this.tagLen = tagLen;
377 this.sub = sub;
378 }
00000379 typeName() {
380 switch (this.tag.tagClass) {
381 case 0: // universal
···415 case 3: return 'Private_' + this.tag.tagNumber.toString();
416 }
417 }
418- /** A string preview of the content (intended for humans). */
00000419 content(maxLength) {
420 if (this.tag === undefined)
421 return null;
422 if (maxLength === undefined)
423 maxLength = Infinity;
424- let content = this.posContent(),
425 len = Math.abs(this.length);
426 if (!this.tag.isUniversal()) {
427 if (this.sub !== null)
···431 }
432 switch (this.tag.tagNumber) {
433 case 0x01: // BOOLEAN
0434 return (this.stream.get(content) === 0) ? 'false' : 'true';
435 case 0x02: // INTEGER
0436 return this.stream.parseInteger(content, content + len);
437 case 0x03: { // BIT_STRING
438 let d = recurse(this, 'parseBitString', maxLength);
···444 }
445 //case 0x05: // NULL
446 case 0x06: // OBJECT_IDENTIFIER
0447 return this.stream.parseOID(content, content + len, maxLength);
448 //case 0x07: // ObjectDescriptor
449 //case 0x08: // EXTERNAL
···480 }
481 return null;
482 }
00000483 toString() {
484 return this.typeName() + '@' + this.stream.pos + '[header:' + this.header + ',length:' + this.length + ',sub:' + ((this.sub === null) ? 'null' : this.sub.length) + ']';
485 }
000000486 toPrettyString(indent) {
487 if (indent === undefined) indent = '';
488- let s = indent + this.typeName() + ' @' + this.stream.pos;
000000000489 if (this.length >= 0)
490 s += '+';
491 s += this.length;
···504 }
505 return s;
506 }
00000507 posStart() {
508 return this.stream.pos;
509 }
00000510 posContent() {
511 return this.stream.pos + this.header;
512 }
00000513 posEnd() {
514 return this.stream.pos + this.header + Math.abs(this.length);
515 }
516- /** Position of the length. */
0000517 posLen() {
518 return this.stream.pos + this.tagLen;
519 }
520- toHexString() {
521- return this.stream.hexDump(this.posStart(), this.posEnd(), true);
000000522 }
523- toB64String() {
524- return this.stream.b64Dump(this.posStart(), this.posEnd());
000000525 }
0000000526 static decodeLength(stream) {
527- let buf = stream.get(),
528 len = buf & 0x7F;
529 if (len == buf) // first bit was 0, short form
530 return len;
531 if (len === 0) // long form with length 0 is a special case
532 return null; // undefined length
533- if (len > 6) // no reason to use Int10, as it would be a huge buffer anyways
534- throw 'Length over 48 bits not supported at position ' + (stream.pos - 1);
535- buf = 0;
536 for (let i = 0; i < len; ++i)
537- buf = (buf * 256) + stream.get();
538- return buf;
539 }
000000000540 static decode(stream, offset, type = ASN1) {
541 if (!(type == ASN1 || type.prototype instanceof ASN1))
542- throw 'Must pass a class that extends ASN1';
543 if (!(stream instanceof Stream))
544 stream = new Stream(stream, offset || 0);
545 let streamStart = new Stream(stream),
···555 // definite length
556 let end = start + len;
557 if (end > stream.enc.length)
558- throw 'Container at offset ' + start + ' has a length of ' + len + ', which is past the end of the stream';
559 while (stream.pos < end)
560 sub[sub.length] = type.decode(stream);
561 if (stream.pos != end)
562- throw 'Content size is not correct for container at offset ' + start;
563 } else {
564 // undefined length
565 try {
···571 }
572 len = start - stream.pos; // undefined lengths are represented as negative values
573 } catch (e) {
574- throw 'Exception while decoding undefined length content at offset ' + start + ': ' + e;
575 }
576 }
577 };
···583 try {
584 if (tag.tagNumber == 0x03)
585 if (stream.get() != 0)
586- throw 'BIT STRINGs with unused bits cannot encapsulate.';
587 getSub();
588- for (let i = 0; i < sub.length; ++i)
589- if (sub[i].tag.isEOC())
590- throw 'EOC is not supposed to be actual content.';
591- } catch (e) {
000000592 // but silently ignore when they don't
593 sub = null;
594 //DEBUG console.log('Could not decode structure at ' + start + ':', e);
···596 }
597 if (sub === null) {
598 if (len === null)
599- throw "We can't skip over an invalid tag with undefined length at offset " + start;
600 stream.pos = start + Math.abs(len);
601 }
602 return new type(streamStart, header, len, tag, tagLen, sub);
···1// ASN.1 JavaScript decoder
2+// Copyright (c) 2008 Lapo Luchini <lapo@lapo.it>
34// Permission to use, copy, modify, and/or distribute this software for any
5// purpose with or without fee is hereby granted, provided that the above
6// copyright notice and this permission notice appear in all copies.
7+//
8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
···13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15016import { oids } from './oids.js';
1718const
···20 reTimeS = /^(\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|(-(?:0\d|1[0-2])|[+](?:0\d|1[0-4]))([0-5]\d)?)?$/,
21 reTimeL = /^(\d\d\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|(-(?:0\d|1[0-2])|[+](?:0\d|1[0-4]))([0-5]\d)?)?$/,
22 hexDigits = '0123456789ABCDEF',
23+ b64Std = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
24+ b64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
25 tableT61 = [
26 ['', ''],
27 ['AEIOUaeiou', 'รรรรรร รจรฌรฒรน'], // Grave
···41 ['CDELNRSTZcdelnrstz', 'ฤฤฤฤฝลลล ลคลฝฤฤฤฤพลลลกลฅลพ'], // Caron
42 ];
4344+/**
45+ * Truncates a string to a specified length and adds an ellipsis if needed.
46+ * @param {string} str - The input string to truncate
47+ * @param {number} len - The maximum length of the string
48+ * @returns {string} The truncated string
49+ */
50function stringCut(str, len) {
51 if (str.length > len)
52 str = str.substring(0, len) + ellipsis;
53 return str;
54}
5556+/**
57+ * Checks if a string contains only printable characters (ASCII 32-126, plus tab, newline, carriage return)
58+ * @param {string} s - The string to check
59+ * @throws {Error} If an unprintable character is found
60+ */
61function checkPrintable(s) {
62 let i, v;
63 for (i = 0; i < s.length; ++i) {
···67 }
68}
6970+/**
71+ * Class to manage a stream of bytes, with a zero-copy approach.
72+ * It uses an existing array or binary string and advances a position index.
73+ */
74+export class Stream {
7576+ /**
77+ * Creates a new Stream object.
78+ * @param {Stream|array|string} enc data (will not be copied)
79+ * @param {?number} pos starting position (mandatory when `end` is not a Stream)
80+ */
81 constructor(enc, pos) {
82 if (enc instanceof Stream) {
83 this.enc = enc.enc;
84 this.pos = enc.pos;
85 } else {
086 this.enc = enc;
87 this.pos = pos;
88 }
89+ if (typeof this.pos != 'number')
90+ throw new Error('"pos" must be a numeric value');
91+ // Set up the raw byte access function based on the type of data
92+ if (typeof this.enc == 'string')
93+ this.getRaw = pos => this.enc.charCodeAt(pos);
94+ else if (typeof this.enc[0] == 'number')
95+ this.getRaw = pos => this.enc[pos];
96+ else
97+ throw new Error('"enc" must be a numeric array or a string');
98 }
99+100+ /**
101+ * Get the byte at current position (and increment it) or at a specified position (and avoid moving current position).
102+ * @param {?number} pos read position if specified, else current position (and increment it)
103+ * @returns {number} The byte value at the specified position
104+ */
105 get(pos) {
106 if (pos === undefined)
107 pos = this.pos++;
108 if (pos >= this.enc.length)
109+ throw new Error('Requesting byte offset ' + pos + ' on a stream of length ' + this.enc.length);
110+ return this.getRaw(pos);
111 }
112+113+ /**
114+ * Convert a single byte to a hexadecimal string (of length 2).
115+ * @param {number} b - The byte to convert
116+ * @returns {string} Hexadecimal representation of the byte
117+ */
118+ static hexByte(b) {
119 return hexDigits.charAt((b >> 4) & 0xF) + hexDigits.charAt(b & 0xF);
120 }
121+122+ /**
123+ * Hexadecimal dump of a specified region of the stream.
124+ * @param {number} start - starting position (included)
125+ * @param {number} end - ending position (excluded)
126+ * @param {string} type - 'raw', 'byte' or 'dump' (default)
127+ * @returns {string} Hexadecimal representation of the data
128+ */
129+ hexDump(start, end, type = 'dump') {
130 let s = '';
131 for (let i = start; i < end; ++i) {
132+ if (type == 'byte' && i > start)
133+ s += ' ';
134+ s += Stream.hexByte(this.get(i));
135+ if (type == 'dump')
136 switch (i & 0xF) {
137 case 0x7: s += ' '; break;
138 case 0xF: s += '\n'; break;
···141 }
142 return s;
143 }
144+145+ /**
146+ * Base64url dump of a specified region of the stream (according to RFC 4648 section 5).
147+ * @param {number} start - starting position (included)
148+ * @param {number} end - ending position (excluded)
149+ * @param {string} type - 'url' (default, section 5 without padding) or 'std' (section 4 with padding)
150+ * @returns {string} Base64 encoded representation of the data
151+ */
152+ b64Dump(start, end, type = 'url') {
153+ const b64 = type === 'url' ? b64URL : b64Std,
154+ extra = (end - start) % 3;
155+ let s = '',
156 i, c;
157 for (i = start; i + 2 < end; i += 3) {
158 c = this.get(i) << 16 | this.get(i + 1) << 8 | this.get(i + 2);
159+ s += b64.charAt(c >> 18 & 0x3F);
160+ s += b64.charAt(c >> 12 & 0x3F);
161+ s += b64.charAt(c >> 6 & 0x3F);
162+ s += b64.charAt(c & 0x3F);
163 }
164 if (extra > 0) {
165 c = this.get(i) << 16;
166 if (extra > 1) c |= this.get(i + 1) << 8;
167+ s += b64.charAt(c >> 18 & 0x3F);
168+ s += b64.charAt(c >> 12 & 0x3F);
169+ if (extra == 2) s += b64.charAt(c >> 6 & 0x3F);
170+ if (b64 === b64Std) s += '==='.slice(0, 3 - extra);
171 }
172 return s;
173 }
174+175+ /**
176+ * Check if a region of the stream contains only ASCII characters (32-176)
177+ * @param {number} start - starting position (included)
178+ * @param {number} end - ending position (excluded)
179+ * @returns {boolean} True if all characters are ASCII, false otherwise
180+ */
181 isASCII(start, end) {
182 for (let i = start; i < end; ++i) {
183 let c = this.get(i);
···186 }
187 return true;
188 }
189+190+ /**
191+ * Parse a region of the stream as an ISO string
192+ * @param {number} start - starting position (included)
193+ * @param {number} end - ending position (excluded)
194+ * @param {number} maxLength - maximum length of the output string
195+ * @returns {Object} Object with size and str properties
196+ */
197 parseStringISO(start, end, maxLength) {
198 let s = '';
199 for (let i = start; i < end; ++i)
200 s += String.fromCharCode(this.get(i));
201 return { size: s.length, str: stringCut(s, maxLength) };
202 }
203+204+ /**
205+ * Parse a region of the stream as a T.61 string
206+ * @param {number} start - starting position (included)
207+ * @param {number} end - ending position (excluded)
208+ * @param {number} maxLength - maximum length of the output string
209+ * @returns {Object} Object with size and str properties
210+ */
211 parseStringT61(start, end, maxLength) {
212 // warning: this code is not very well tested so far
213 function merge(c, d) {
214+ const t = tableT61[c - 0xC0];
215+ const i = t[0].indexOf(String.fromCharCode(d));
216 return (i < 0) ? '\0' : t[1].charAt(i);
217 }
218 let s = '', c;
···229 }
230 return { size: s.length, str: stringCut(s, maxLength) };
231 }
232+233+ /**
234+ * Parse a region of the stream as a UTF-8 string
235+ * @param {number} start - starting position (included)
236+ * @param {number} end - ending position (excluded)
237+ * @param {number} maxLength - maximum length of the output string
238+ * @returns {Object} Object with size and str properties
239+ */
240 parseStringUTF(start, end, maxLength) {
241+ /**
242+ * Helper function to process UTF-8 continuation bytes
243+ * @param {number} c - The continuation byte
244+ * @returns {number} The extracted data bits
245+ */
246 function ex(c) { // must be 10xxxxxx
247 if ((c < 0x80) || (c >= 0xC0))
248 throw new Error('Invalid UTF-8 continuation byte: ' + c);
249 return (c & 0x3F);
250 }
251+ /**
252+ * Helper function to convert a code point to a surrogate pair
253+ * @param {number} cp - The code point to convert
254+ * @returns {string} The surrogate pair as a string
255+ */
256 function surrogate(cp) {
257 if (cp < 0x10000)
258 throw new Error('UTF-8 overlong encoding, codepoint encoded in 4 bytes: ' + cp);
···262 }
263 let s = '';
264 for (let i = start; i < end; ) {
265+ const c = this.get(i++);
266 if (c < 0x80) // 0xxxxxxx (7 bit)
267 s += String.fromCharCode(c);
268 else if (c < 0xC0)
···278 }
279 return { size: s.length, str: stringCut(s, maxLength) };
280 }
281+282+ /**
283+ * Parse a region of the stream as a BMP (Basic Multilingual Plane) string
284+ * @param {number} start - starting position (included)
285+ * @param {number} end - ending position (excluded)
286+ * @param {number} maxLength - maximum length of the output string
287+ * @returns {Object} Object with size and str properties
288+ */
289 parseStringBMP(start, end, maxLength) {
290 let s = '', hi, lo;
291 for (let i = start; i < end; ) {
···295 }
296 return { size: s.length, str: stringCut(s, maxLength) };
297 }
298+299+ /**
300+ * Parse a region of the stream as a time string
301+ * @param {number} start - starting position (included)
302+ * @param {number} end - ending position (excluded)
303+ * @param {boolean} shortYear - Whether to parse as short year (2-digit)
304+ * @returns {string} Formatted time string
305+ */
306 parseTime(start, end, shortYear) {
307 let s = this.parseStringISO(start, end).str,
308 m = (shortYear ? reTimeS : reTimeL).exec(s);
309 if (!m)
310+ throw new Error('Unrecognized time: ' + s);
311 if (shortYear) {
312 // to avoid querying the timer, use the fixed range [1970, 2069]
313 // it will conform with ITU X.400 [-10, +40] sliding window until 2030
···330 }
331 return s;
332 }
333+334+ /**
335+ * Parse a region of the stream as an integer
336+ * @param {number} start - starting position (included)
337+ * @param {number} end - ending position (excluded)
338+ * @returns {string} Formatted integer string
339+ */
340 parseInteger(start, end) {
341 let v = this.get(start),
000342 s = '';
343+ const neg = (v > 127),
344+ pad = neg ? 255 : 0;
345 // skip unuseful bits (not allowed in DER)
346 while (v == pad && ++start < end)
347 v = this.get(start);
348+ const len = end - start;
349 if (len === 0)
350 return neg ? '-1' : '0';
351 // show bit length of huge integers
352 if (len > 4) {
353+ let v2 = v,
354+ lenBit = len << 3;
355+ while (((v2 ^ pad) & 0x80) == 0) {
356+ v2 <<= 1;
357+ --lenBit;
358 }
359+ s = '(' + lenBit + ' bit)\n';
360 }
361 // decode the integer
362 if (neg) v = v - 256;
363+ let n = BigInt(v);
364 for (let i = start + 1; i < end; ++i)
365+ n = (n << 8n) | BigInt(this.get(i));
366+ return s + n;
367 }
368+369+ /**
370+ * Parse a region of the stream as a bit string.
371+ * @param {number} start - starting position (included)
372+ * @param {number} end - ending position (excluded)
373+ * @param {number} maxLength - maximum length of the output string
374+ * @returns {Object} Object with size and str properties
375+ */
376 parseBitString(start, end, maxLength) {
377+ const unusedBits = this.get(start);
378 if (unusedBits > 7)
379+ throw new Error('Invalid BitString with unusedBits=' + unusedBits);
380+ const lenBit = ((end - start - 1) << 3) - unusedBits;
381+ let s = '';
382 for (let i = start + 1; i < end; ++i) {
383 let b = this.get(i),
384 skip = (i == end - 1) ? unusedBits : 0;
···389 }
390 return { size: lenBit, str: s };
391 }
392+393+ /**
394+ * Parse a region of the stream as an octet string.
395+ * @param {number} start - starting position (included)
396+ * @param {number} end - ending position (excluded)
397+ * @param {number} maxLength - maximum length of the output string
398+ * @returns {Object} Object with size and str properties
399+ */
400 parseOctetString(start, end, maxLength) {
00401 try {
402+ let s = this.parseStringUTF(start, end, maxLength);
403 checkPrintable(s.str);
404 return { size: end - start, str: s.str };
405+ } catch (ignore) {
406+ // If UTF-8 parsing fails, fall back to hexadecimal dump
407 }
408+ const len = end - start;
409 maxLength /= 2; // we work in bytes
410 if (len > maxLength)
411 end = start + maxLength;
412+ let s = '';
413 for (let i = start; i < end; ++i)
414+ s += Stream.hexByte(this.get(i));
415 if (len > maxLength)
416 s += ellipsis;
417 return { size: len, str: s };
418 }
419+420+ /**
421+ * Parse a region of the stream as an OID (Object Identifier).
422+ * @param {number} start - starting position (included)
423+ * @param {number} end - ending position (excluded)
424+ * @param {number} maxLength - maximum length of the output string
425+ * @param {boolean} isRelative - Whether the OID is relative
426+ * @returns {string} Formatted OID string
427+ */
428 parseOID(start, end, maxLength, isRelative) {
429 let s = '',
430+ n = 0n,
431 bits = 0;
432 for (let i = start; i < end; ++i) {
433 let v = this.get(i);
434+ // Shift bits and add the lower 7 bits of the byte
435+ n = (n << 7n) | BigInt(v & 0x7F);
436 bits += 7;
437+ // If the most significant bit is 0, this is the last byte of the OID component
438 if (!(v & 0x80)) { // finished
439+ // If this is the first component, handle it specially
440 if (s === '') {
0441 if (isRelative) {
442+ s = n.toString();
000443 } else {
444+ let m = n < 80 ? n < 40 ? 0n : 1n : 2n;
445+ s = m + '.' + (n - m * 40n);
446 }
447 } else
448+ s += '.' + n;
449 if (s.length > maxLength)
450 return stringCut(s, maxLength);
451+ n = 0n;
452 bits = 0;
453 }
454 }
455 if (bits > 0)
456 s += '.incomplete';
457+ // If OIDs mapping is available and the OID is absolute, try to resolve it
458 if (typeof oids === 'object' && !isRelative) {
459 let oid = oids[s];
460 if (oid) {
···465 }
466 return s;
467 }
468+469+ /**
470+ * Parse a region of the stream as a relative OID (Object Identifier).
471+ * @param {number} start - starting position (included)
472+ * @param {number} end - ending position (excluded)
473+ * @param {number} maxLength - maximum length of the output string
474+ * @returns {string} Formatted relative OID string
475+ */
476 parseRelativeOID(start, end, maxLength) {
477 return this.parseOID(start, end, maxLength, true);
478 }
···505 this.tagConstructed = ((buf & 0x20) !== 0);
506 this.tagNumber = buf & 0x1F;
507 if (this.tagNumber == 0x1F) { // long tag
508+ let n = 0n;
509 do {
510 buf = stream.get();
511+ n = (n << 7n) | BigInt(buf & 0x7F);
512 } while (buf & 0x80);
513+ this.tagNumber = n <= Number.MAX_SAFE_INTEGER ? Number(n) : n;
514 }
515 }
516 isUniversal() {
···521 }
522}
523524+/**
525+ * ASN1 class for parsing ASN.1 encoded data.
526+ * Instances of this class represent an ASN.1 element and provides methods to parse and display its content.
527+ */
528export class ASN1 {
529+ /**
530+ * Creates an ASN1 parser object.
531+ * @param {Stream} stream - The stream containing the ASN.1 data.
532+ * @param {number} header - The header length.
533+ * @param {number} length - The length of the data.
534+ * @param {ASN1Tag} tag - The ASN.1 tag.
535+ * @param {number} tagLen - The length of the tag.
536+ * @param {Array} sub - The sub-elements.
537+ */
538 constructor(stream, header, length, tag, tagLen, sub) {
539+ if (!(tag instanceof ASN1Tag)) throw new Error('Invalid tag value.');
540 this.stream = stream;
541 this.header = header;
542 this.length = length;
···544 this.tagLen = tagLen;
545 this.sub = sub;
546 }
547+548+ /**
549+ * Get the type name of the ASN.1 element.
550+ * @returns {string} The type name.
551+ */
552 typeName() {
553 switch (this.tag.tagClass) {
554 case 0: // universal
···588 case 3: return 'Private_' + this.tag.tagNumber.toString();
589 }
590 }
591+592+ /**
593+ * Get a string preview of the content (intended for humans).
594+ * @param {number} maxLength - The maximum length of the content.
595+ * @returns {string|null} The content preview or null if not supported.
596+ */
597 content(maxLength) {
598 if (this.tag === undefined)
599 return null;
600 if (maxLength === undefined)
601 maxLength = Infinity;
602+ const content = this.posContent(),
603 len = Math.abs(this.length);
604 if (!this.tag.isUniversal()) {
605 if (this.sub !== null)
···609 }
610 switch (this.tag.tagNumber) {
611 case 0x01: // BOOLEAN
612+ if (len != 1) return 'invalid length ' + len;
613 return (this.stream.get(content) === 0) ? 'false' : 'true';
614 case 0x02: // INTEGER
615+ if (len < 1) return 'invalid length ' + len;
616 return this.stream.parseInteger(content, content + len);
617 case 0x03: { // BIT_STRING
618 let d = recurse(this, 'parseBitString', maxLength);
···624 }
625 //case 0x05: // NULL
626 case 0x06: // OBJECT_IDENTIFIER
627+ if (len < 1) return 'invalid length ' + len; // pgut001's dumpasn1.c enforces a minimum lenght of 3
628 return this.stream.parseOID(content, content + len, maxLength);
629 //case 0x07: // ObjectDescriptor
630 //case 0x08: // EXTERNAL
···661 }
662 return null;
663 }
664+665+ /**
666+ * Get a string representation of the ASN.1 element.
667+ * @returns {string} The string representation.
668+ */
669 toString() {
670 return this.typeName() + '@' + this.stream.pos + '[header:' + this.header + ',length:' + this.length + ',sub:' + ((this.sub === null) ? 'null' : this.sub.length) + ']';
671 }
672+673+ /**
674+ * Get a pretty string representation of the ASN.1 element.
675+ * @param {string} indent - The indentation string.
676+ * @returns {string} The pretty string representation.
677+ */
678 toPrettyString(indent) {
679 if (indent === undefined) indent = '';
680+ let s = indent;
681+ if (this.def) {
682+ if (this.def.id)
683+ s += this.def.id + ' ';
684+ if (this.def.name && this.def.name != this.typeName().replace(/_/g, ' '))
685+ s+= this.def.name + ' ';
686+ if (this.def.mismatch)
687+ s += '[?] ';
688+ }
689+ s += this.typeName() + ' @' + this.stream.pos;
690 if (this.length >= 0)
691 s += '+';
692 s += this.length;
···705 }
706 return s;
707 }
708+709+ /**
710+ * Get the starting position of the element in the stream.
711+ * @returns {number} The starting position.
712+ */
713 posStart() {
714 return this.stream.pos;
715 }
716+717+ /**
718+ * Get the position of the content in the stream.
719+ * @returns {number} The content position.
720+ */
721 posContent() {
722 return this.stream.pos + this.header;
723 }
724+725+ /**
726+ * Get the ending position of the element in the stream.
727+ * @returns {number} The ending position.
728+ */
729 posEnd() {
730 return this.stream.pos + this.header + Math.abs(this.length);
731 }
732+733+ /**
734+ * Get the position of the length in the stream.
735+ * @returns {number} The length position.
736+ */
737 posLen() {
738 return this.stream.pos + this.tagLen;
739 }
740+741+ /**
742+ * Get a hexadecimal dump of the node.
743+ * @param {string} [type='raw'] - The dump type: 'raw', 'byte', or 'dump'.
744+ * @returns {string} The hexadecimal dump.
745+ */
746+ toHexString(type = 'raw') {
747+ return this.stream.hexDump(this.posStart(), this.posEnd(), type);
748 }
749+750+ /**
751+ * Get a base64url dump of the node (according to RFC 4648 section 5).
752+ * @param {string} [type='url'] - The dump type: 'url' (section 5 without padding) or 'std' (section 4 with padding).
753+ * @returns {string} The base64 encoded representation.
754+ */
755+ toB64String(type = 'url') {
756+ return this.stream.b64Dump(this.posStart(), this.posEnd(), type);
757 }
758+759+ /**
760+ * Decode the length field of an ASN.1 element.
761+ * @param {Stream} stream - The stream to read from.
762+ * @returns {number|null} The decoded length, or null for indefinite length.
763+ * @throws {Error} If the length is invalid or exceeds 48 bits.
764+ */
765 static decodeLength(stream) {
766+ const buf = stream.get(),
767 len = buf & 0x7F;
768 if (len == buf) // first bit was 0, short form
769 return len;
770 if (len === 0) // long form with length 0 is a special case
771 return null; // undefined length
772+ if (len > 6) // no reason to use BigInt, as it would be a huge buffer anyways
773+ throw new Error('Length over 48 bits not supported at position ' + (stream.pos - 1));
774+ let value = 0;
775 for (let i = 0; i < len; ++i)
776+ value = (value << 8) | stream.get();
777+ return value;
778 }
779+780+ /**
781+ * Decode an ASN.1 element from a stream.
782+ * @param {Stream|array|string} stream - The input data.
783+ * @param {number} [offset=0] - The offset to start decoding from.
784+ * @param {Function} [type=ASN1] - The class to instantiate.
785+ * @returns {ASN1} The decoded ASN.1 element.
786+ * @throws {Error} If the decoding fails.
787+ */
788 static decode(stream, offset, type = ASN1) {
789 if (!(type == ASN1 || type.prototype instanceof ASN1))
790+ throw new Error('Must pass a class that extends ASN1');
791 if (!(stream instanceof Stream))
792 stream = new Stream(stream, offset || 0);
793 let streamStart = new Stream(stream),
···803 // definite length
804 let end = start + len;
805 if (end > stream.enc.length)
806+ throw new Error('Container at offset ' + start + ' has a length of ' + len + ', which is past the end of the stream');
807 while (stream.pos < end)
808 sub[sub.length] = type.decode(stream);
809 if (stream.pos != end)
810+ throw new Error('Content size is not correct for container at offset ' + start);
811 } else {
812 // undefined length
813 try {
···819 }
820 len = start - stream.pos; // undefined lengths are represented as negative values
821 } catch (e) {
822+ throw new Error('Exception while decoding undefined length content at offset ' + start + ': ' + e);
823 }
824 }
825 };
···831 try {
832 if (tag.tagNumber == 0x03)
833 if (stream.get() != 0)
834+ throw new Error('BIT STRINGs with unused bits cannot encapsulate.');
835 getSub();
836+ for (let s of sub) {
837+ if (s.tag.isEOC())
838+ throw new Error('EOC is not supposed to be actual content.');
839+ try {
840+ s.content();
841+ } catch (e) {
842+ throw new Error('Unable to parse content: ' + e);
843+ }
844+ }
845+ } catch (ignore) {
846 // but silently ignore when they don't
847 sub = null;
848 //DEBUG console.log('Could not decode structure at ' + start + ':', e);
···850 }
851 if (sub === null) {
852 if (len === null)
853+ throw new Error("We can't skip over an invalid tag with undefined length at offset " + start);
854 stream.pos = start + Math.abs(len);
855 }
856 return new type(streamStart, header, len, tag, tagLen, sub);
+8-7
base64.js
···1// Base64 JavaScript decoder
2-// Copyright (c) 2008-2024 Lapo Luchini <lapo@lapo.it>
34// Permission to use, copy, modify, and/or distribute this software for any
5// purpose with or without fee is hereby granted, provided that the above
6// copyright notice and this permission notice appear in all copies.
7-//
8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
···31 decoder[b64.charCodeAt(i)] = i;
32 for (i = 0; i < ignore.length; ++i)
33 decoder[ignore.charCodeAt(i)] = -1;
34- // RFC 3548 URL & file safe encoding
35 decoder['-'.charCodeAt(0)] = decoder['+'.charCodeAt(0)];
36 decoder['_'.charCodeAt(0)] = decoder['/'.charCodeAt(0)];
37 }
···7576 static pretty(str) {
77 // fix padding
78- if (str.length % 4 > 0)
79- str = (str + '===').slice(0, str.length + str.length % 4);
80- // convert RFC 3548 to standard Base64
081 str = str.replace(/-/g, '+').replace(/_/g, '/');
82 // 80 column width
83- return str.replace(/(.{80})/g, '$1\n');
84 }
8586 static unarmor(a) {
···1// Base64 JavaScript decoder
2+// Copyright (c) 2008 Lapo Luchini <lapo@lapo.it>
34// Permission to use, copy, modify, and/or distribute this software for any
5// purpose with or without fee is hereby granted, provided that the above
6// copyright notice and this permission notice appear in all copies.
7+//
8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
···31 decoder[b64.charCodeAt(i)] = i;
32 for (i = 0; i < ignore.length; ++i)
33 decoder[ignore.charCodeAt(i)] = -1;
34+ // also support decoding Base64url (RFC 4648 section 5)
35 decoder['-'.charCodeAt(0)] = decoder['+'.charCodeAt(0)];
36 decoder['_'.charCodeAt(0)] = decoder['/'.charCodeAt(0)];
37 }
···7576 static pretty(str) {
77 // fix padding
78+ let pad = 4 - str.length % 4;
79+ if (pad < 4)
80+ str += '==='.slice(0, pad);
81+ // convert Base64url (RFC 4648 section 5) to standard Base64 (RFC 4648 section 4)
82 str = str.replace(/-/g, '+').replace(/_/g, '/');
83 // 80 column width
84+ return str.replace(/.{80}/g, '$&\n');
85 }
8687 static unarmor(a) {
···1+This is a PKCS#7/CMS encrypted with passwod.
2+$ echo content | openssl cms -encrypt -pwri_password test -aes256 -outform pem -out examples/cms-password.p7m
3+-----BEGIN CMS-----
4+MIHYBgkqhkiG9w0BBwOggcowgccCAQMxgYOjgYACAQCgGwYJKoZIhvcNAQUMMA4E
5+CED/DSxXMtH6AgIIADAsBgsqhkiG9w0BCRADCTAdBglghkgBZQMEASoEEDIQbJMC
6+Sfb3LpwHduj/meQEMKwrwq5M4V0stztm6OUTAsFY2zKDY20SApwSEeEcAh9TM42E
7+1palnHeqHTBpC8pIpjA8BgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEqBBByt+scPrdM
8+giR7WUOJyB3hgBDcD3UDMtZSep8X/3yy1/Yq
9+-----END CMS-----
+12
examples/crl-rfc5280.b64
···000000000000
···1+CRL example from RFC5280 as found here:
2+https://csrc.nist.gov/projects/pki-testing/sample-certificates-and-crls
3+4+begin-base64 644 crl-rfc5280.der
5+MIIBYDCBygIBATANBgkqhkiG9w0BAQUFADBDMRMwEQYKCZImiZPyLGQBGRYDY29tMRcwFQYKCZIm
6+iZPyLGQBGRYHZXhhbXBsZTETMBEGA1UEAxMKRXhhbXBsZSBDQRcNMDUwMjA1MTIwMDAwWhcNMDUw
7+MjA2MTIwMDAwWjAiMCACARIXDTA0MTExOTE1NTcwM1owDDAKBgNVHRUEAwoBAaAvMC0wHwYDVR0j
8+BBgwFoAUCGivhTPIOUp6+IKTjnBqSiCELDIwCgYDVR0UBAMCAQwwDQYJKoZIhvcNAQEFBQADgYEA
9+ItwYffcIzsx10NBqm60Q9HYjtIFutW2+DvsVFGzIF20f7pAXom9g5L2qjFXejoRvkvifEBInr0rU
10+L4XiNkR9qqNMJTgV/wD9Pn7uPSYS69jnK2LiK8NGgO94gtEVxtCccmrLznrtZ5mLbnCBfUNCdMGm
11+r8FVF6IzTNYGmCuk/C4=
12+====
+45
examples/crl-rfc5280.b64.dump
···000000000000000000000000000000000000000000000
···1+CertificateList SEQUENCE @0+352 (constructed): (3 elem)
2+ tbsCertList TBSCertList SEQUENCE @4+202 (constructed): (7 elem)
3+ version Version INTEGER @7+1: 1
4+ signature AlgorithmIdentifier SEQUENCE @10+13 (constructed): (2 elem)
5+ algorithm OBJECT_IDENTIFIER @12+9: 1.2.840.113549.1.1.5|sha1WithRSAEncryption|PKCS #1
6+ parameters ANY NULL @23+0
7+ issuer rdnSequence Name SEQUENCE @25+67 (constructed): (3 elem)
8+ RelativeDistinguishedName SET @27+19 (constructed): (1 elem)
9+ AttributeTypeAndValue SEQUENCE @29+17 (constructed): (2 elem)
10+ type AttributeType OBJECT_IDENTIFIER @31+10: 0.9.2342.19200300.100.1.25|domainComponent|Men are from Mars, this OID is from Pluto
11+ value AttributeValue [?] IA5String @43+3: com
12+ RelativeDistinguishedName SET @48+23 (constructed): (1 elem)
13+ AttributeTypeAndValue SEQUENCE @50+21 (constructed): (2 elem)
14+ type AttributeType OBJECT_IDENTIFIER @52+10: 0.9.2342.19200300.100.1.25|domainComponent|Men are from Mars, this OID is from Pluto
15+ value AttributeValue [?] IA5String @64+7: example
16+ RelativeDistinguishedName SET @73+19 (constructed): (1 elem)
17+ AttributeTypeAndValue SEQUENCE @75+17 (constructed): (2 elem)
18+ type AttributeType OBJECT_IDENTIFIER @77+3: 2.5.4.3|commonName|X.520 DN component
19+ value AttributeValue [?] PrintableString @82+10: Example CA
20+ thisUpdate utcTime Time UTCTime @94+13: 2005-02-05 12:00:00 UTC
21+ nextUpdate utcTime Time UTCTime @109+13: 2005-02-06 12:00:00 UTC
22+ revokedCertificates SEQUENCE @124+34 (constructed): (1 elem)
23+ SEQUENCE @126+32 (constructed): (3 elem)
24+ userCertificate CertificateSerialNumber INTEGER @128+1: 18
25+ revocationDate utcTime Time UTCTime @131+13: 2004-11-19 15:57:03 UTC
26+ crlEntryExtensions Extensions SEQUENCE @146+12 (constructed): (1 elem)
27+ Extension SEQUENCE @148+10 (constructed): (2 elem)
28+ extnID OBJECT_IDENTIFIER @150+3: 2.5.29.21|cRLReason|X.509 extension
29+ extnValue OCTET_STRING @155+3 (encapsulates): (3 byte)|0A0101
30+ ENUMERATED @157+1: 1
31+ crlExtensions [0] @160+47 (constructed): (1 elem)
32+ Extensions SEQUENCE @162+45 (constructed): (2 elem)
33+ Extension SEQUENCE @164+31 (constructed): (2 elem)
34+ extnID OBJECT_IDENTIFIER @166+3: 2.5.29.35|authorityKeyIdentifier|X.509 extension
35+ extnValue OCTET_STRING @171+24 (encapsulates): (24 byte)|301680140868AF8533C8394A7AF882938E706A4A20842C32
36+ SEQUENCE @173+22 (constructed): (1 elem)
37+ [0] @175+20: (20 byte)|0868AF8533C8394A7AF882938E706A4A20842C32
38+ Extension SEQUENCE @197+10 (constructed): (2 elem)
39+ extnID OBJECT_IDENTIFIER @199+3: 2.5.29.20|cRLNumber|X.509 extension
40+ extnValue OCTET_STRING @204+3 (encapsulates): (3 byte)|02010C
41+ INTEGER @206+1: 12
42+ signatureAlgorithm AlgorithmIdentifier SEQUENCE @209+13 (constructed): (2 elem)
43+ algorithm OBJECT_IDENTIFIER @211+9: 1.2.840.113549.1.1.5|sha1WithRSAEncryption|PKCS #1
44+ parameters ANY NULL @222+0
45+ signature BIT_STRING @224+129: (1024 bit)|0010001011011100000110000111110111110111000010001100111011001100011101011101000011010000011010101001101110101101000100001111010001110110001000111011010010000001011011101011010101101101101111100000111011111011000101010001010001101100110010000001011101101101000111111110111010010000000101111010001001101111011000001110010010111101101010101000110001010101110111101000111010000100011011111001001011111000100111110001000000010010001001111010111101001010110101000010111110000101111000100011011001000100011111011010101010100011010011000010010100111000000101011111111100000000111111010011111001111110111011100011110100100110000100101110101111011000111001110010101101100010111000100010101111000011010001101000000011101111011110001000001011010001000101011100011011010000100111000111001001101010110010111100111001111010111011010110011110011001100010110110111001110000100000010111110101000011010000100111010011000001101001101010111111000001010101010001011110100010001100110100110011010110000001101001100000101011101001001111110000101110
···1+LDAPMessage example as found on ldap.com.
2+3+Original link:
4+https://ldap.com/ldapv3-wire-protocol-reference-ldap-message/
5+6+begin-base64 644 ldapmessage.der
7+MDUCAQVKEWRjPWV4YW1wbGUsZGM9Y29toB0wGwQWMS4yLjg0MC4xMTM1NTYuMS40LjgwNQEB/w==
8+====
···1// Hex JavaScript decoder
2-// Copyright (c) 2008-2024 Lapo Luchini <lapo@lapo.it>
34// Permission to use, copy, modify, and/or distribute this software for any
5// purpose with or without fee is hereby granted, provided that the above
6// copyright notice and this permission notice appear in all copies.
7-//
8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
···1// Hex JavaScript decoder
2+// Copyright (c) 2008 Lapo Luchini <lapo@lapo.it>
34// Permission to use, copy, modify, and/or distribute this software for any
5// purpose with or without fee is hereby granted, provided that the above
6// copyright notice and this permission notice appear in all copies.
7+//
8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
···01import { ASN1DOM } from './dom.js';
2import { Base64 } from './base64.js';
3import { Hex } from './hex.js';
···15 area = id('area'),
16 file = id('file'),
17 examples = id('examples'),
18- selectTheme = id('theme-select'),
19 selectDefs = id('definitions'),
20 selectTag = id('tags');
21···41function show(asn1) {
42 tree.innerHTML = '';
43 dump.innerHTML = '';
44- tree.appendChild(asn1.toDOM());
00045 if (wantHex.checked) dump.appendChild(asn1.toHexDOM(undefined, trimHex.checked));
46}
47-function decode(der, offset) {
48 offset = offset || 0;
49 try {
50 const asn1 = ASN1DOM.decode(der, offset);
···83 if (area.value === '') area.value = Base64.pretty(b64);
84 try {
85 window.location.hash = hash = '#' + b64;
86- } catch (e) {
87 // fails with "Access Denied" on IE with URLs longer than ~2048 chars
88 window.location.hash = hash = '#';
89 }
···103 text(tree, e);
104 }
105}
106-function decodeText(val) {
107 try {
108 let der = reHex.test(val) ? Hex.decode(val) : Base64.unarmor(val);
109 decode(der);
···112 dump.innerHTML = '';
113 }
114}
115-function decodeBinaryString(str) {
116 let der;
117 try {
118 if (reHex.test(str)) der = Hex.decode(str);
119 else if (Base64.re.test(str)) der = Base64.unarmor(str);
120 else der = str;
121 decode(der);
122- } catch (e) {
123 text(tree, 'Cannot decode file.');
124 dump.innerHTML = '';
125 }
126}
127// set up buttons
128-id('butDecode').onclick = function () {
129- decodeText(area.value);
0000000000000000000000000130};
131-id('butClear').onclick = function () {
132- area.value = '';
133- file.value = '';
134- tree.innerHTML = '';
135- dump.innerHTML = '';
136- selectDefs.innerHTML = '';
137- hash = window.location.hash = '';
138-};
139-id('butExample').onclick = function () {
140- console.log('Loading example:', examples.value);
141- let request = new XMLHttpRequest();
142- request.open('GET', 'examples/' + examples.value, true);
143- request.onreadystatechange = function () {
144- if (this.readyState !== 4) return;
145- if (this.status >= 200 && this.status < 400) {
146- area.value = this.responseText;
147- decodeText(this.responseText);
148- } else {
149- console.log('Error loading example.');
150- }
151- };
152- request.send();
153-};
154-// set dark theme depending on OS settings
155-function setTheme() {
156- let storedTheme = localStorage.getItem('theme');
157- let theme = 'os';
158- if (storedTheme)
159- theme = storedTheme;
160- selectTheme.value = theme;
161- if (theme == 'os') {
162- let prefersDarkScheme = window.matchMedia('(prefers-color-scheme: dark)');
163- theme = prefersDarkScheme.matches ? 'dark': 'light';
164- }
165- if (theme == 'dark') {
166- const css1 = id('theme-base');
167- const css2 = css1.cloneNode();
168- css2.id = 'theme-override';
169- css2.href = 'index-' + theme + '.css';
170- css1.parentElement.appendChild(css2);
171- } else {
172- const css2 = id('theme-override');
173- if (css2) css2.remove();
174- }
175}
176-setTheme();
177-selectTheme.addEventListener('change', function () {
178- localStorage.setItem('theme', selectTheme.value);
179- setTheme();
180-});
181// this is only used if window.FileReader
182function read(f) {
183 area.value = ''; // clear text area, will get b64 content
···1+import './theme.js';
2import { ASN1DOM } from './dom.js';
3import { Base64 } from './base64.js';
4import { Hex } from './hex.js';
···16 area = id('area'),
17 file = id('file'),
18 examples = id('examples'),
019 selectDefs = id('definitions'),
20 selectTag = id('tags');
21···41function show(asn1) {
42 tree.innerHTML = '';
43 dump.innerHTML = '';
44+ let ul = document.createElement('ul');
45+ ul.className = 'treecollapse';
46+ tree.appendChild(ul);
47+ ul.appendChild(asn1.toDOM());
48 if (wantHex.checked) dump.appendChild(asn1.toHexDOM(undefined, trimHex.checked));
49}
50+export function decode(der, offset) {
51 offset = offset || 0;
52 try {
53 const asn1 = ASN1DOM.decode(der, offset);
···86 if (area.value === '') area.value = Base64.pretty(b64);
87 try {
88 window.location.hash = hash = '#' + b64;
89+ } catch (ignore) {
90 // fails with "Access Denied" on IE with URLs longer than ~2048 chars
91 window.location.hash = hash = '#';
92 }
···106 text(tree, e);
107 }
108}
109+export function decodeText(val) {
110 try {
111 let der = reHex.test(val) ? Hex.decode(val) : Base64.unarmor(val);
112 decode(der);
···115 dump.innerHTML = '';
116 }
117}
118+export function decodeBinaryString(str) {
119 let der;
120 try {
121 if (reHex.test(str)) der = Hex.decode(str);
122 else if (Base64.re.test(str)) der = Base64.unarmor(str);
123 else der = str;
124 decode(der);
125+ } catch (ignore) {
126 text(tree, 'Cannot decode file.');
127 dump.innerHTML = '';
128 }
129}
130// set up buttons
131+const butClickHandlers = {
132+ butDecode: () => {
133+ decodeText(area.value);
134+ },
135+ butClear: () => {
136+ area.value = '';
137+ file.value = '';
138+ tree.innerHTML = '';
139+ dump.innerHTML = '';
140+ selectDefs.innerHTML = '';
141+ hash = window.location.hash = '';
142+ },
143+ butExample: () => {
144+ console.log('Loading example:', examples.value);
145+ let request = new XMLHttpRequest();
146+ request.open('GET', 'examples/' + examples.value, true);
147+ request.onreadystatechange = function () {
148+ if (this.readyState !== 4) return;
149+ if (this.status >= 200 && this.status < 400) {
150+ area.value = this.responseText;
151+ decodeText(this.responseText);
152+ } else {
153+ console.log('Error loading example.');
154+ }
155+ };
156+ request.send();
157+ },
158};
159+for (const [name, onClick] of Object.entries(butClickHandlers)) {
160+ let elem = id(name);
161+ if (elem)
162+ elem.onclick = onClick;
0000000000000000000000000000000000000000163}
00000164// this is only used if window.FileReader
165function read(f) {
166 area.value = ''; // clear text area, will get b64 content
-106
int10.js
···1-// Big integer base-10 printing library
2-// Copyright (c) 2008-2024 Lapo Luchini <lapo@lapo.it>
3-4-// Permission to use, copy, modify, and/or distribute this software for any
5-// purpose with or without fee is hereby granted, provided that the above
6-// copyright notice and this permission notice appear in all copies.
7-//
8-// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9-// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10-// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11-// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12-// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13-// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14-// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15-16-let max = 10000000000000; // biggest 10^n integer that can still fit 2^53 when multiplied by 256
17-18-export class Int10 {
19- /**
20- * Arbitrary length base-10 value.
21- * @param {number} value - Optional initial value (will be 0 otherwise).
22- */
23- constructor(value) {
24- this.buf = [+value || 0];
25- }
26-27- /**
28- * Multiply value by m and add c.
29- * @param {number} m - multiplier, must be < =256
30- * @param {number} c - value to add
31- */
32- mulAdd(m, c) {
33- // assert(m <= 256)
34- let b = this.buf,
35- l = b.length,
36- i, t;
37- for (i = 0; i < l; ++i) {
38- t = b[i] * m + c;
39- if (t < max)
40- c = 0;
41- else {
42- c = 0|(t / max);
43- t -= c * max;
44- }
45- b[i] = t;
46- }
47- if (c > 0)
48- b[i] = c;
49- }
50-51- /**
52- * Subtract value.
53- * @param {number} c - value to subtract
54- */
55- sub(c) {
56- let b = this.buf,
57- l = b.length,
58- i, t;
59- for (i = 0; i < l; ++i) {
60- t = b[i] - c;
61- if (t < 0) {
62- t += max;
63- c = 1;
64- } else
65- c = 0;
66- b[i] = t;
67- }
68- while (b[b.length - 1] === 0)
69- b.pop();
70- }
71-72- /**
73- * Convert to decimal string representation.
74- * @param {*} base - optional value, only value accepted is 10
75- */
76- toString(base) {
77- if ((base || 10) != 10)
78- throw 'only base 10 is supported';
79- let b = this.buf,
80- s = b[b.length - 1].toString();
81- for (let i = b.length - 2; i >= 0; --i)
82- s += (max + b[i]).toString().substring(1);
83- return s;
84- }
85-86- /**
87- * Convert to Number value representation.
88- * Will probably overflow 2^53 and thus become approximate.
89- */
90- valueOf() {
91- let b = this.buf,
92- v = 0;
93- for (let i = b.length - 1; i >= 0; --i)
94- v = v * max + b[i];
95- return v;
96- }
97-98- /**
99- * Return value as a simple Number (if it is <= 10000000000000), or return this.
100- */
101- simplify() {
102- let b = this.buf;
103- return (b.length == 1) ? b[0] : this;
104- }
105-106-}