@lapo/asn1js 2.1.1 → 2.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  ISC License
2
2
 
3
- Copyright (c) 2008-2025 Lapo Luchini <lapo@lapo.it>
3
+ Copyright (c) 2008-2026 Lapo Luchini <lapo@lapo.it>
4
4
 
5
5
  Permission to use, copy, modify, and/or distribute this software for any
6
6
  purpose with or without fee is hereby granted, provided that the above
package/README.md CHANGED
@@ -81,7 +81,7 @@ npx @lapo/asn1js ed25519.cer
81
81
  ISC license
82
82
  -----------
83
83
 
84
- ASN.1 JavaScript decoder Copyright (c) 2008-2025 Lapo Luchini <lapo@lapo.it>
84
+ ASN.1 JavaScript decoder Copyright (c) 2008-2026 Lapo Luchini <lapo@lapo.it>
85
85
 
86
86
  Permission 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
87
 
package/asn1.js CHANGED
@@ -13,13 +13,12 @@
13
13
  // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14
14
  // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
15
 
16
- import { Int10 } from './int10.js';
17
16
  import { oids } from './oids.js';
18
17
 
19
18
  const
20
19
  ellipsis = '\u2026',
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)?)?$/,
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,}))?)?)?(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,}))?)?)?(Z|(-(?:0\d|1[0-2])|[+](?:0\d|1[0-4]))([0-5]\d)?)?$/,
23
22
  hexDigits = '0123456789ABCDEF',
24
23
  b64Std = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
25
24
  b64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
@@ -42,12 +41,23 @@ const
42
41
  ['CDELNRSTZcdelnrstz', 'ČĎĚĽŇŘŠŤŽčďěľňřšťž'], // Caron
43
42
  ];
44
43
 
44
+ /**
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
+ */
45
50
  function stringCut(str, len) {
46
51
  if (str.length > len)
47
52
  str = str.substring(0, len) + ellipsis;
48
53
  return str;
49
54
  }
50
55
 
56
+ /**
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
+ */
51
61
  function checkPrintable(s) {
52
62
  let i, v;
53
63
  for (i = 0; i < s.length; ++i) {
@@ -57,13 +67,16 @@ function checkPrintable(s) {
57
67
  }
58
68
  }
59
69
 
60
- /** 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. */
70
+ /**
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
+ */
62
74
  export class Stream {
63
75
 
64
76
  /**
77
+ * Creates a new Stream object.
65
78
  * @param {Stream|array|string} enc data (will not be copied)
66
- * @param {?number} pos starting position (mandatory when `end` is not a Stream)
79
+ * @param {?number} pos starting position (mandatory when `enc` is not a Stream)
67
80
  */
68
81
  constructor(enc, pos) {
69
82
  if (enc instanceof Stream) {
@@ -75,6 +88,7 @@ export class Stream {
75
88
  }
76
89
  if (typeof this.pos != 'number')
77
90
  throw new Error('"pos" must be a numeric value');
91
+ // Set up the raw byte access function based on the type of data
78
92
  if (typeof this.enc == 'string')
79
93
  this.getRaw = pos => this.enc.charCodeAt(pos);
80
94
  else if (typeof this.enc[0] == 'number')
@@ -82,8 +96,12 @@ export class Stream {
82
96
  else
83
97
  throw new Error('"enc" must be a numeric array or a string');
84
98
  }
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) */
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
+ */
87
105
  get(pos) {
88
106
  if (pos === undefined)
89
107
  pos = this.pos++;
@@ -91,15 +109,23 @@ export class Stream {
91
109
  throw new Error('Requesting byte offset ' + pos + ' on a stream of length ' + this.enc.length);
92
110
  return this.getRaw(pos);
93
111
  }
94
- /** Convert a single byte to an hexadcimal string (of length 2).
95
- * @param {number} b */
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
+ */
96
118
  static hexByte(b) {
97
119
  return hexDigits.charAt((b >> 4) & 0xF) + hexDigits.charAt(b & 0xF);
98
120
  }
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) */
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
+ */
103
129
  hexDump(start, end, type = 'dump') {
104
130
  let s = '';
105
131
  for (let i = start; i < end; ++i) {
@@ -115,14 +141,18 @@ export class Stream {
115
141
  }
116
142
  return s;
117
143
  }
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) */
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
+ */
122
152
  b64Dump(start, end, type = 'url') {
123
- const b64 = type === 'url' ? b64URL : b64Std;
124
- let extra = (end - start) % 3,
125
- s = '',
153
+ const b64 = type === 'url' ? b64URL : b64Std,
154
+ extra = (end - start) % 3;
155
+ let s = '',
126
156
  i, c;
127
157
  for (i = start; i + 2 < end; i += 3) {
128
158
  c = this.get(i) << 16 | this.get(i + 1) << 8 | this.get(i + 2);
@@ -141,6 +171,13 @@ export class Stream {
141
171
  }
142
172
  return s;
143
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
+ */
144
181
  isASCII(start, end) {
145
182
  for (let i = start; i < end; ++i) {
146
183
  let c = this.get(i);
@@ -149,17 +186,33 @@ export class Stream {
149
186
  }
150
187
  return true;
151
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
+ */
152
197
  parseStringISO(start, end, maxLength) {
153
198
  let s = '';
154
199
  for (let i = start; i < end; ++i)
155
200
  s += String.fromCharCode(this.get(i));
156
201
  return { size: s.length, str: stringCut(s, maxLength) };
157
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
+ */
158
211
  parseStringT61(start, end, maxLength) {
159
212
  // warning: this code is not very well tested so far
160
213
  function merge(c, d) {
161
- let t = tableT61[c - 0xC0];
162
- let i = t[0].indexOf(String.fromCharCode(d));
214
+ const t = tableT61[c - 0xC0];
215
+ const i = t[0].indexOf(String.fromCharCode(d));
163
216
  return (i < 0) ? '\0' : t[1].charAt(i);
164
217
  }
165
218
  let s = '', c;
@@ -176,12 +229,30 @@ export class Stream {
176
229
  }
177
230
  return { size: s.length, str: stringCut(s, maxLength) };
178
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
+ */
179
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
+ */
180
246
  function ex(c) { // must be 10xxxxxx
181
247
  if ((c < 0x80) || (c >= 0xC0))
182
248
  throw new Error('Invalid UTF-8 continuation byte: ' + c);
183
249
  return (c & 0x3F);
184
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
+ */
185
256
  function surrogate(cp) {
186
257
  if (cp < 0x10000)
187
258
  throw new Error('UTF-8 overlong encoding, codepoint encoded in 4 bytes: ' + cp);
@@ -191,7 +262,7 @@ export class Stream {
191
262
  }
192
263
  let s = '';
193
264
  for (let i = start; i < end; ) {
194
- let c = this.get(i++);
265
+ const c = this.get(i++);
195
266
  if (c < 0x80) // 0xxxxxxx (7 bit)
196
267
  s += String.fromCharCode(c);
197
268
  else if (c < 0xC0)
@@ -207,6 +278,14 @@ export class Stream {
207
278
  }
208
279
  return { size: s.length, str: stringCut(s, maxLength) };
209
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
+ */
210
289
  parseStringBMP(start, end, maxLength) {
211
290
  let s = '', hi, lo;
212
291
  for (let i = start; i < end; ) {
@@ -216,6 +295,14 @@ export class Stream {
216
295
  }
217
296
  return { size: s.length, str: stringCut(s, maxLength) };
218
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
+ */
219
306
  parseTime(start, end, shortYear) {
220
307
  let s = this.parseStringISO(start, end).str,
221
308
  m = (shortYear ? reTimeS : reTimeL).exec(s);
@@ -243,41 +330,55 @@ export class Stream {
243
330
  }
244
331
  return s;
245
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
+ */
246
340
  parseInteger(start, end) {
247
341
  let v = this.get(start),
248
- neg = (v > 127),
249
- pad = neg ? 255 : 0,
250
- len,
251
342
  s = '';
343
+ const neg = (v > 127),
344
+ pad = neg ? 255 : 0;
252
345
  // skip unuseful bits (not allowed in DER)
253
346
  while (v == pad && ++start < end)
254
347
  v = this.get(start);
255
- len = end - start;
348
+ const len = end - start;
256
349
  if (len === 0)
257
350
  return neg ? '-1' : '0';
258
351
  // show bit length of huge integers
259
352
  if (len > 4) {
260
- s = v;
261
- len <<= 3;
262
- while (((s ^ pad) & 0x80) == 0) {
263
- s <<= 1;
264
- --len;
353
+ let v2 = v,
354
+ lenBit = len << 3;
355
+ while (((v2 ^ pad) & 0x80) == 0) {
356
+ v2 <<= 1;
357
+ --lenBit;
265
358
  }
266
- s = '(' + len + ' bit)\n';
359
+ s = '(' + lenBit + ' bit)\n';
267
360
  }
268
361
  // decode the integer
269
362
  if (neg) v = v - 256;
270
- let n = new Int10(v);
363
+ let n = BigInt(v);
271
364
  for (let i = start + 1; i < end; ++i)
272
- n.mulAdd(256, this.get(i));
273
- return s + n.toString();
365
+ n = (n << 8n) | BigInt(this.get(i));
366
+ return s + n;
274
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
+ */
275
376
  parseBitString(start, end, maxLength) {
276
- let unusedBits = this.get(start);
377
+ const unusedBits = this.get(start);
277
378
  if (unusedBits > 7)
278
379
  throw new Error('Invalid BitString with unusedBits=' + unusedBits);
279
- let lenBit = ((end - start - 1) << 3) - unusedBits,
280
- s = '';
380
+ const lenBit = ((end - start - 1) << 3) - unusedBits;
381
+ let s = '';
281
382
  for (let i = start + 1; i < end; ++i) {
282
383
  let b = this.get(i),
283
384
  skip = (i == end - 1) ? unusedBits : 0;
@@ -288,56 +389,72 @@ export class Stream {
288
389
  }
289
390
  return { size: lenBit, str: s };
290
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
+ */
291
400
  parseOctetString(start, end, maxLength) {
292
- let len = end - start,
293
- s;
294
401
  try {
295
- s = this.parseStringUTF(start, end, maxLength);
402
+ let s = this.parseStringUTF(start, end, maxLength);
296
403
  checkPrintable(s.str);
297
404
  return { size: end - start, str: s.str };
298
405
  } catch (ignore) {
299
- // ignore
406
+ // If UTF-8 parsing fails, fall back to hexadecimal dump
300
407
  }
408
+ const len = end - start;
301
409
  maxLength /= 2; // we work in bytes
302
410
  if (len > maxLength)
303
411
  end = start + maxLength;
304
- s = '';
412
+ let s = '';
305
413
  for (let i = start; i < end; ++i)
306
414
  s += Stream.hexByte(this.get(i));
307
415
  if (len > maxLength)
308
416
  s += ellipsis;
309
417
  return { size: len, str: s };
310
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
+ */
311
428
  parseOID(start, end, maxLength, isRelative) {
312
429
  let s = '',
313
- n = new Int10(),
430
+ n = 0n,
314
431
  bits = 0;
315
432
  for (let i = start; i < end; ++i) {
316
433
  let v = this.get(i);
317
- n.mulAdd(128, v & 0x7F);
434
+ // Shift bits and add the lower 7 bits of the byte
435
+ n = (n << 7n) | BigInt(v & 0x7F);
318
436
  bits += 7;
437
+ // If the most significant bit is 0, this is the last byte of the OID component
319
438
  if (!(v & 0x80)) { // finished
439
+ // If this is the first component, handle it specially
320
440
  if (s === '') {
321
- n = n.simplify();
322
441
  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();
442
+ s = n.toString();
327
443
  } else {
328
- let m = n < 80 ? n < 40 ? 0 : 1 : 2;
329
- s = m + '.' + (n - m * 40);
444
+ let m = n < 80 ? n < 40 ? 0n : 1n : 2n;
445
+ s = m + '.' + (n - m * 40n);
330
446
  }
331
447
  } else
332
- s += '.' + n.toString();
448
+ s += '.' + n;
333
449
  if (s.length > maxLength)
334
450
  return stringCut(s, maxLength);
335
- n = new Int10();
451
+ n = 0n;
336
452
  bits = 0;
337
453
  }
338
454
  }
339
455
  if (bits > 0)
340
456
  s += '.incomplete';
457
+ // If OIDs mapping is available and the OID is absolute, try to resolve it
341
458
  if (typeof oids === 'object' && !isRelative) {
342
459
  let oid = oids[s];
343
460
  if (oid) {
@@ -348,6 +465,14 @@ export class Stream {
348
465
  }
349
466
  return s;
350
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
+ */
351
476
  parseRelativeOID(start, end, maxLength) {
352
477
  return this.parseOID(start, end, maxLength, true);
353
478
  }
@@ -380,12 +505,12 @@ class ASN1Tag {
380
505
  this.tagConstructed = ((buf & 0x20) !== 0);
381
506
  this.tagNumber = buf & 0x1F;
382
507
  if (this.tagNumber == 0x1F) { // long tag
383
- let n = new Int10();
508
+ let n = 0n;
384
509
  do {
385
510
  buf = stream.get();
386
- n.mulAdd(128, buf & 0x7F);
511
+ n = (n << 7n) | BigInt(buf & 0x7F);
387
512
  } while (buf & 0x80);
388
- this.tagNumber = n.simplify();
513
+ this.tagNumber = n <= Number.MAX_SAFE_INTEGER ? Number(n) : n;
389
514
  }
390
515
  }
391
516
  isUniversal() {
@@ -396,7 +521,20 @@ class ASN1Tag {
396
521
  }
397
522
  }
398
523
 
524
+ /**
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
+ */
399
528
  export 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
+ */
400
538
  constructor(stream, header, length, tag, tagLen, sub) {
401
539
  if (!(tag instanceof ASN1Tag)) throw new Error('Invalid tag value.');
402
540
  this.stream = stream;
@@ -406,6 +544,11 @@ export class ASN1 {
406
544
  this.tagLen = tagLen;
407
545
  this.sub = sub;
408
546
  }
547
+
548
+ /**
549
+ * Get the type name of the ASN.1 element.
550
+ * @returns {string} The type name.
551
+ */
409
552
  typeName() {
410
553
  switch (this.tag.tagClass) {
411
554
  case 0: // universal
@@ -445,13 +588,18 @@ export class ASN1 {
445
588
  case 3: return 'Private_' + this.tag.tagNumber.toString();
446
589
  }
447
590
  }
448
- /** A string preview of the content (intended for humans). */
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
+ */
449
597
  content(maxLength) {
450
598
  if (this.tag === undefined)
451
599
  return null;
452
600
  if (maxLength === undefined)
453
601
  maxLength = Infinity;
454
- let content = this.posContent(),
602
+ const content = this.posContent(),
455
603
  len = Math.abs(this.length);
456
604
  if (!this.tag.isUniversal()) {
457
605
  if (this.sub !== null)
@@ -513,9 +661,20 @@ export class ASN1 {
513
661
  }
514
662
  return null;
515
663
  }
664
+
665
+ /**
666
+ * Get a string representation of the ASN.1 element.
667
+ * @returns {string} The string representation.
668
+ */
516
669
  toString() {
517
670
  return this.typeName() + '@' + this.stream.pos + '[header:' + this.header + ',length:' + this.length + ',sub:' + ((this.sub === null) ? 'null' : this.sub.length) + ']';
518
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
+ */
519
678
  toPrettyString(indent) {
520
679
  if (indent === undefined) indent = '';
521
680
  let s = indent;
@@ -546,44 +705,86 @@ export class ASN1 {
546
705
  }
547
706
  return s;
548
707
  }
708
+
709
+ /**
710
+ * Get the starting position of the element in the stream.
711
+ * @returns {number} The starting position.
712
+ */
549
713
  posStart() {
550
714
  return this.stream.pos;
551
715
  }
716
+
717
+ /**
718
+ * Get the position of the content in the stream.
719
+ * @returns {number} The content position.
720
+ */
552
721
  posContent() {
553
722
  return this.stream.pos + this.header;
554
723
  }
724
+
725
+ /**
726
+ * Get the ending position of the element in the stream.
727
+ * @returns {number} The ending position.
728
+ */
555
729
  posEnd() {
556
730
  return this.stream.pos + this.header + Math.abs(this.length);
557
731
  }
558
- /** Position of the length. */
732
+
733
+ /**
734
+ * Get the position of the length in the stream.
735
+ * @returns {number} The length position.
736
+ */
559
737
  posLen() {
560
738
  return this.stream.pos + this.tagLen;
561
739
  }
562
- /** Hexadecimal dump of the node.
563
- * @param type 'raw', 'byte' or 'dump' */
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
+ */
564
746
  toHexString(type = 'raw') {
565
747
  return this.stream.hexDump(this.posStart(), this.posEnd(), type);
566
748
  }
567
- /** Base64url dump of the node (according to RFC 4648 section 5).
568
- * @param {string} type 'url' (default, section 5 without padding) or 'std' (section 4 with padding)
569
- */
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
+ */
570
755
  toB64String(type = 'url') {
571
756
  return this.stream.b64Dump(this.posStart(), this.posEnd(), type);
572
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
+ */
573
765
  static decodeLength(stream) {
574
- let buf = stream.get(),
766
+ const buf = stream.get(),
575
767
  len = buf & 0x7F;
576
768
  if (len == buf) // first bit was 0, short form
577
769
  return len;
578
770
  if (len === 0) // long form with length 0 is a special case
579
771
  return null; // undefined length
580
- if (len > 6) // no reason to use Int10, as it would be a huge buffer anyways
772
+ if (len > 6) // no reason to use BigInt, as it would be a huge buffer anyways
581
773
  throw new Error('Length over 48 bits not supported at position ' + (stream.pos - 1));
582
- buf = 0;
774
+ let value = 0;
583
775
  for (let i = 0; i < len; ++i)
584
- buf = (buf * 256) + stream.get();
585
- return buf;
776
+ value = (value * 256) + stream.get();
777
+ return value;
586
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
+ */
587
788
  static decode(stream, offset, type = ASN1) {
588
789
  if (!(type == ASN1 || type.prototype instanceof ASN1))
589
790
  throw new Error('Must pass a class that extends ASN1');
@@ -594,15 +795,13 @@ export class ASN1 {
594
795
  tagLen = stream.pos - streamStart.pos,
595
796
  len = ASN1.decodeLength(stream),
596
797
  start = stream.pos,
798
+ end = (len !== null) ? (start + len) : null,
597
799
  header = start - streamStart.pos,
598
800
  sub = null,
599
801
  getSub = function () {
600
802
  sub = [];
601
803
  if (len !== null) {
602
804
  // definite length
603
- let end = start + len;
604
- if (end > stream.enc.length)
605
- throw new Error('Container at offset ' + start + ' has a length of ' + len + ', which is past the end of the stream');
606
805
  while (stream.pos < end)
607
806
  sub[sub.length] = type.decode(stream);
608
807
  if (stream.pos != end)
@@ -622,6 +821,8 @@ export class ASN1 {
622
821
  }
623
822
  }
624
823
  };
824
+ if (end !== null && end > stream.enc.length)
825
+ throw new Error('Element at offset ' + start + ' has a length of ' + len + ', which is past the end of the stream');
625
826
  if (tag.tagConstructed) {
626
827
  // must have valid content
627
828
  getSub();
package/dumpASN1.js CHANGED
@@ -3,8 +3,10 @@
3
3
  // usage:
4
4
  // ./dumpASN1.js filename
5
5
  // ./dumpASN1.js data:base64,MDMCAQFjLgQACgEACgEAAgEAAgEAAQEAoA+jDQQFTnRWZXIEBAEAAAAwCgQITmV0bG9nb24===
6
+ // cat file.der | ./dumpASN1.js -
6
7
 
7
8
  import * as fs from 'node:fs';
9
+ import { text as streamAsString } from 'node:stream/consumers';
8
10
  import { Base64 } from './base64.js';
9
11
  import { ASN1 } from './asn1.js';
10
12
  import { Defs } from './defs.js';
@@ -46,10 +48,14 @@ function print(value, indent) {
46
48
  }
47
49
 
48
50
  const filename = process.argv[2];
51
+ let content;
49
52
  const match = reDataURI.exec(filename);
50
- let content = match
51
- ? Buffer.from(match[1])
52
- : fs.readFileSync(filename);
53
+ if (match)
54
+ content = Buffer.from(match[1]);
55
+ else if (filename == '-') // stdin
56
+ content = await streamAsString(process.stdin);
57
+ else
58
+ content = fs.readFileSync(filename);
53
59
  try { // try PEM first
54
60
  content = Base64.unarmor(content);
55
61
  } catch (ignore) { // try DER/BER then
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lapo/asn1js",
3
- "version": "2.1.1",
3
+ "version": "2.1.3",
4
4
  "description": "Generic ASN.1 parser/decoder that can decode any valid ASN.1 DER or BER structures.",
5
5
  "type": "module",
6
6
  "main": "asn1.js",
@@ -24,7 +24,6 @@
24
24
  "asn1.js",
25
25
  "base64.js",
26
26
  "hex.js",
27
- "int10.js",
28
27
  "dom.js",
29
28
  "defs.js",
30
29
  "oids.js",
@@ -32,7 +31,7 @@
32
31
  "dumpASN1.js"
33
32
  ],
34
33
  "scripts": {
35
- "lint": "npx eslint asn1.js base64.js hex.js int10.js dom.js defs.js oids.js rfcdef.js tags.js context.js index.js parseRFC.js dumpASN1.js test.js testDefs.js vite.config.js theme.js",
34
+ "lint": "npx eslint asn1.js base64.js hex.js dom.js defs.js oids.js rfcdef.js tags.js context.js index.js parseRFC.js dumpASN1.js test.js testDefs.js vite.config.js theme.js",
36
35
  "lint-action": "npx @action-validator/cli .github/workflows/node.js.yml",
37
36
  "build": "vite build",
38
37
  "serve": "npx -p local-web-server ws",
@@ -47,14 +46,14 @@
47
46
  },
48
47
  "packageManager": "pnpm@7.33.7",
49
48
  "devDependencies": {
50
- "@eslint/eslintrc": "^3.3.1",
51
- "@eslint/js": "^9.38.0",
52
- "@rollup/wasm-node": "^4.52.5",
53
- "diff": "^8.0.2",
54
- "eslint": "^9.38.0",
55
- "globals": "^16.4.0",
49
+ "@eslint/eslintrc": "^3.3.4",
50
+ "@eslint/js": "^9.39.3",
51
+ "@rollup/wasm-node": "^4.59.0",
52
+ "diff": "^8.0.3",
53
+ "eslint": "^9.39.3",
54
+ "globals": "^16.5.0",
56
55
  "htmlparser2": "^9.1.0",
57
- "vite": "^5.4.21",
56
+ "vite": "^7.3.1",
58
57
  "vite-plugin-dom": "^1.0.5",
59
58
  "vite-plugin-singlefile": "^2.3.0"
60
59
  },
@@ -63,8 +62,7 @@
63
62
  },
64
63
  "pnpm": {
65
64
  "overrides": {
66
- "rollup": "npm:@rollup/wasm-node",
67
- "esbuild@<=0.24.2": ">=0.25.0"
65
+ "rollup": "npm:@rollup/wasm-node"
68
66
  }
69
67
  }
70
68
  }
package/int10.js DELETED
@@ -1,112 +0,0 @@
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
- }