···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
···101links
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)
+273-69
asn1.js
···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
···42 ['CDELNRSTZcdelnrstz', 'ฤฤฤฤฝลลล ลคลฝฤฤฤฤพลลลกลฅลพ'], // Caron
43 ];
4400000045function stringCut(str, len) {
46 if (str.length > len)
47 str = str.substring(0, len) + ellipsis;
48 return str;
49}
500000051function checkPrintable(s) {
52 let i, v;
53 for (i = 0; i < s.length; ++i) {
···57 }
58}
5960-/** Class to manage a stream of bytes, with a zero-copy approach.
61- * It uses an existing array or binary string and advances a position index. */
0062export class Stream {
6364 /**
065 * @param {Stream|array|string} enc data (will not be copied)
66 * @param {?number} pos starting position (mandatory when `end` is not a Stream)
67 */
···75 }
76 if (typeof this.pos != 'number')
77 throw new Error('"pos" must be a numeric value');
078 if (typeof this.enc == 'string')
79 this.getRaw = pos => this.enc.charCodeAt(pos);
80 else if (typeof this.enc[0] == 'number')
···82 else
83 throw new Error('"enc" must be a numeric array or a string');
84 }
85- /** Get the byte at current position (and increment it) or at a specified position (and avoid moving current position).
86- * @param {?number} pos read position if specified, else current position (and increment it) */
000087 get(pos) {
88 if (pos === undefined)
89 pos = this.pos++;
···91 throw new Error('Requesting byte offset ' + pos + ' on a stream of length ' + this.enc.length);
92 return this.getRaw(pos);
93 }
94- /** Convert a single byte to an hexadcimal string (of length 2).
95- * @param {number} b */
000096 static hexByte(b) {
97 return hexDigits.charAt((b >> 4) & 0xF) + hexDigits.charAt(b & 0xF);
98 }
99- /** Hexadecimal dump of a specified region of the stream.
100- * @param {number} start starting position (included)
101- * @param {number} end ending position (excluded)
102- * @param {string} type 'raw', 'byte' or 'dump' (default) */
0000103 hexDump(start, end, type = 'dump') {
104 let s = '';
105 for (let i = start; i < end; ++i) {
···115 }
116 return s;
117 }
118- /** Base64url dump of a specified region of the stream (according to RFC 4648 section 5).
119- * @param {number} start starting position (included)
120- * @param {number} end ending position (excluded)
121- * @param {string} type 'url' (default, section 5 without padding) or 'std' (section 4 with padding) */
0000122 b64Dump(start, end, type = 'url') {
123- const b64 = type === 'url' ? b64URL : b64Std;
124- let extra = (end - start) % 3,
125- s = '',
126 i, c;
127 for (i = start; i + 2 < end; i += 3) {
128 c = this.get(i) << 16 | this.get(i + 1) << 8 | this.get(i + 2);
···141 }
142 return s;
143 }
0000000144 isASCII(start, end) {
145 for (let i = start; i < end; ++i) {
146 let c = this.get(i);
···149 }
150 return true;
151 }
00000000152 parseStringISO(start, end, maxLength) {
153 let s = '';
154 for (let i = start; i < end; ++i)
155 s += String.fromCharCode(this.get(i));
156 return { size: s.length, str: stringCut(s, maxLength) };
157 }
00000000158 parseStringT61(start, end, maxLength) {
159 // warning: this code is not very well tested so far
160 function merge(c, d) {
161- let t = tableT61[c - 0xC0];
162- let i = t[0].indexOf(String.fromCharCode(d));
163 return (i < 0) ? '\0' : t[1].charAt(i);
164 }
165 let s = '', c;
···176 }
177 return { size: s.length, str: stringCut(s, maxLength) };
178 }
00000000179 parseStringUTF(start, end, maxLength) {
00000180 function ex(c) { // must be 10xxxxxx
181 if ((c < 0x80) || (c >= 0xC0))
182 throw new Error('Invalid UTF-8 continuation byte: ' + c);
183 return (c & 0x3F);
184 }
00000185 function surrogate(cp) {
186 if (cp < 0x10000)
187 throw new Error('UTF-8 overlong encoding, codepoint encoded in 4 bytes: ' + cp);
···191 }
192 let s = '';
193 for (let i = start; i < end; ) {
194- let c = this.get(i++);
195 if (c < 0x80) // 0xxxxxxx (7 bit)
196 s += String.fromCharCode(c);
197 else if (c < 0xC0)
···207 }
208 return { size: s.length, str: stringCut(s, maxLength) };
209 }
00000000210 parseStringBMP(start, end, maxLength) {
211 let s = '', hi, lo;
212 for (let i = start; i < end; ) {
···216 }
217 return { size: s.length, str: stringCut(s, maxLength) };
218 }
00000000219 parseTime(start, end, shortYear) {
220 let s = this.parseStringISO(start, end).str,
221 m = (shortYear ? reTimeS : reTimeL).exec(s);
···243 }
244 return s;
245 }
0000000246 parseInteger(start, end) {
247 let v = this.get(start),
248- neg = (v > 127),
249- pad = neg ? 255 : 0,
250- len,
251 s = '';
00252 // skip unuseful bits (not allowed in DER)
253 while (v == pad && ++start < end)
254 v = this.get(start);
255- len = end - start;
256 if (len === 0)
257 return neg ? '-1' : '0';
258 // show bit length of huge integers
259 if (len > 4) {
260- s = v;
261- len <<= 3;
262- while (((s ^ pad) & 0x80) == 0) {
263- s <<= 1;
264- --len;
265 }
266- s = '(' + len + ' bit)\n';
267 }
268 // decode the integer
269 if (neg) v = v - 256;
270- let n = new Int10(v);
271 for (let i = start + 1; i < end; ++i)
272- n.mulAdd(256, this.get(i));
273- return s + n.toString();
274 }
00000000275 parseBitString(start, end, maxLength) {
276- let unusedBits = this.get(start);
277 if (unusedBits > 7)
278 throw new Error('Invalid BitString with unusedBits=' + unusedBits);
279- let lenBit = ((end - start - 1) << 3) - unusedBits,
280- s = '';
281 for (let i = start + 1; i < end; ++i) {
282 let b = this.get(i),
283 skip = (i == end - 1) ? unusedBits : 0;
···288 }
289 return { size: lenBit, str: s };
290 }
00000000291 parseOctetString(start, end, maxLength) {
292- let len = end - start,
293- s;
294 try {
295- s = this.parseStringUTF(start, end, maxLength);
296 checkPrintable(s.str);
297 return { size: end - start, str: s.str };
298 } catch (ignore) {
299- // ignore
300 }
0301 maxLength /= 2; // we work in bytes
302 if (len > maxLength)
303 end = start + maxLength;
304- s = '';
305 for (let i = start; i < end; ++i)
306 s += Stream.hexByte(this.get(i));
307 if (len > maxLength)
308 s += ellipsis;
309 return { size: len, str: s };
310 }
000000000311 parseOID(start, end, maxLength, isRelative) {
312 let s = '',
313- n = new Int10(),
314 bits = 0;
315 for (let i = start; i < end; ++i) {
316 let v = this.get(i);
317- n.mulAdd(128, v & 0x7F);
0318 bits += 7;
0319 if (!(v & 0x80)) { // finished
0320 if (s === '') {
321- n = n.simplify();
322 if (isRelative) {
323- s = (n instanceof Int10) ? n.toString() : '' + n;
324- } else if (n instanceof Int10) {
325- n.sub(80);
326- s = '2.' + n.toString();
327 } else {
328- let m = n < 80 ? n < 40 ? 0 : 1 : 2;
329- s = m + '.' + (n - m * 40);
330 }
331 } else
332- s += '.' + n.toString();
333 if (s.length > maxLength)
334 return stringCut(s, maxLength);
335- n = new Int10();
336 bits = 0;
337 }
338 }
339 if (bits > 0)
340 s += '.incomplete';
0341 if (typeof oids === 'object' && !isRelative) {
342 let oid = oids[s];
343 if (oid) {
···348 }
349 return s;
350 }
00000000351 parseRelativeOID(start, end, maxLength) {
352 return this.parseOID(start, end, maxLength, true);
353 }
···380 this.tagConstructed = ((buf & 0x20) !== 0);
381 this.tagNumber = buf & 0x1F;
382 if (this.tagNumber == 0x1F) { // long tag
383- let n = new Int10();
384 do {
385 buf = stream.get();
386- n.mulAdd(128, buf & 0x7F);
387 } while (buf & 0x80);
388- this.tagNumber = n.simplify();
389 }
390 }
391 isUniversal() {
···396 }
397}
3980000399export class ASN1 {
000000000400 constructor(stream, header, length, tag, tagLen, sub) {
401 if (!(tag instanceof ASN1Tag)) throw new Error('Invalid tag value.');
402 this.stream = stream;
···406 this.tagLen = tagLen;
407 this.sub = sub;
408 }
00000409 typeName() {
410 switch (this.tag.tagClass) {
411 case 0: // universal
···445 case 3: return 'Private_' + this.tag.tagNumber.toString();
446 }
447 }
448- /** A string preview of the content (intended for humans). */
00000449 content(maxLength) {
450 if (this.tag === undefined)
451 return null;
452 if (maxLength === undefined)
453 maxLength = Infinity;
454- let content = this.posContent(),
455 len = Math.abs(this.length);
456 if (!this.tag.isUniversal()) {
457 if (this.sub !== null)
···461 }
462 switch (this.tag.tagNumber) {
463 case 0x01: // BOOLEAN
0464 return (this.stream.get(content) === 0) ? 'false' : 'true';
465 case 0x02: // INTEGER
0466 return this.stream.parseInteger(content, content + len);
467 case 0x03: { // BIT_STRING
468 let d = recurse(this, 'parseBitString', maxLength);
···474 }
475 //case 0x05: // NULL
476 case 0x06: // OBJECT_IDENTIFIER
0477 return this.stream.parseOID(content, content + len, maxLength);
478 //case 0x07: // ObjectDescriptor
479 //case 0x08: // EXTERNAL
···510 }
511 return null;
512 }
00000513 toString() {
514 return this.typeName() + '@' + this.stream.pos + '[header:' + this.header + ',length:' + this.length + ',sub:' + ((this.sub === null) ? 'null' : this.sub.length) + ']';
515 }
000000516 toPrettyString(indent) {
517 if (indent === undefined) indent = '';
518 let s = indent;
···543 }
544 return s;
545 }
00000546 posStart() {
547 return this.stream.pos;
548 }
00000549 posContent() {
550 return this.stream.pos + this.header;
551 }
00000552 posEnd() {
553 return this.stream.pos + this.header + Math.abs(this.length);
554 }
555- /** Position of the length. */
0000556 posLen() {
557 return this.stream.pos + this.tagLen;
558 }
559- /** Hexadecimal dump of the node.
560- * @param type 'raw', 'byte' or 'dump' */
0000561 toHexString(type = 'raw') {
562 return this.stream.hexDump(this.posStart(), this.posEnd(), type);
563 }
564- /** Base64url dump of the node (according to RFC 4648 section 5).
565- * @param {string} type 'url' (default, section 5 without padding) or 'std' (section 4 with padding)
566- */
000567 toB64String(type = 'url') {
568 return this.stream.b64Dump(this.posStart(), this.posEnd(), type);
569 }
0000000570 static decodeLength(stream) {
571- let buf = stream.get(),
572 len = buf & 0x7F;
573 if (len == buf) // first bit was 0, short form
574 return len;
575 if (len === 0) // long form with length 0 is a special case
576 return null; // undefined length
577- if (len > 6) // no reason to use Int10, as it would be a huge buffer anyways
578 throw new Error('Length over 48 bits not supported at position ' + (stream.pos - 1));
579- buf = 0;
580 for (let i = 0; i < len; ++i)
581- buf = (buf * 256) + stream.get();
582- return buf;
583 }
000000000584 static decode(stream, offset, type = ASN1) {
585 if (!(type == ASN1 || type.prototype instanceof ASN1))
586 throw new Error('Must pass a class that extends ASN1');
···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
···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+ */
74export 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 */
···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')
···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++;
···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) {
···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);
···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);
···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;
···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;
···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');
···1-// Big integer base-10 printing library
2-// Copyright (c) 2008 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-/** Biggest 10^n integer that can still fit 2^53 when multiplied by 256. */
17-const max = 10000000000000;
18-19-export class Int10 {
20- /**
21- * Arbitrary length base-10 value.
22- * @param {number} value - Optional initial value (will be 0 otherwise).
23- */
24- constructor(value) {
25- this.buf = [+value || 0];
26- }
27-28- /**
29- * Multiply value by m and add c.
30- * @param {number} m - multiplier, must be 0<m<=256
31- * @param {number} c - value to add, must be c>=0
32- */
33- mulAdd(m, c) {
34- // assert(m > 0)
35- // assert(m <= 256)
36- // assert(c >= 0)
37- let b = this.buf,
38- l = b.length,
39- i, t;
40- for (i = 0; i < l; ++i) {
41- t = b[i] * m + c;
42- if (t < max)
43- c = 0;
44- else {
45- c = 0|(t / max);
46- t -= c * max;
47- }
48- b[i] = t;
49- }
50- if (c > 0)
51- b[i] = c;
52- }
53-54- /**
55- * Subtract value.
56- * @param {number} c - value to subtract
57- */
58- sub(c) {
59- let b = this.buf,
60- l = b.length,
61- i, t;
62- for (i = 0; i < l; ++i) {
63- t = b[i] - c;
64- if (t < 0) {
65- t += max;
66- c = 1;
67- } else
68- c = 0;
69- b[i] = t;
70- }
71- while (b[b.length - 1] === 0)
72- b.pop();
73- }
74-75- /**
76- * Convert to decimal string representation.
77- * @param {number} [base=10] - optional value, only value accepted is 10
78- * @returns {string} The decimal string representation.
79- */
80- toString(base = 10) {
81- if (base != 10)
82- throw new Error('only base 10 is supported');
83- let b = this.buf,
84- s = b[b.length - 1].toString();
85- for (let i = b.length - 2; i >= 0; --i)
86- s += (max + b[i]).toString().substring(1);
87- return s;
88- }
89-90- /**
91- * Convert to Number value representation.
92- * Will probably overflow 2^53 and thus become approximate.
93- * @returns {number} The numeric value.
94- */
95- valueOf() {
96- let b = this.buf,
97- v = 0;
98- for (let i = b.length - 1; i >= 0; --i)
99- v = v * max + b[i];
100- return v;
101- }
102-103- /**
104- * Return value as a simple Number (if it is <= 10000000000000), or return this.
105- * @returns {number | Int10} The simplified value.
106- */
107- simplify() {
108- let b = this.buf;
109- return (b.length == 1) ? b[0] : this;
110- }
111-112-}