···11+# ChangeLog
22+33+## 2.1.1 - 2025-10-24
44+55+### Changed
66+77+- update dev dependencies
88+- fix test suite that was reporting no error with empty responses
99+1010+### Added
1111+1212+- add content length check for BOOLEAN, INTEGER, OID ([GitHub #104](https://github.com/lapo-luchini/asn1js/pull/104))
1313+1414+## 2.1.0 - 2025-08-03
1515+1616+### Changed
1717+1818+- 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))
1919+- 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
2020+2121+### Added
2222+2323+- add tests to check expected decoding
2424+2525+## 2.0.6 - 2025-07-29
2626+2727+### Added
2828+2929+- add proper support for standard Base64 (we previously only supported Base64url) (fixes [GitHub #99](https://github.com/lapo-luchini/asn1js/pull/99))
3030+- improve test harness
3131+3232+## 2.0.5 - 2025-04-12
3333+3434+### Added
3535+3636+- add `index-local.html` for local `file://` usage without needing a web server
3737+- add definitions support for `LDAPMessage`
3838+- #TODO continue producing old ChangeLog entries
+5-3
README.md
···101101links
102102-----
103103104104-- [official website](https://lapo.it/asn1js/)
105105-- [dedicated domain](https://asn1js.eu/)
106106-- [InDefero tracker](http://idf.lapo.it/p/asn1js/)
104104+- [official website](https://asn1js.eu/)
105105+- [alternate website](https://lapo.it/asn1js/)
106106+- [single-file version working locally](https://asn1js.eu/index-local.html) (just save this link)
107107+- [InDefero tracker](http://idf.lapo.it/p/asn1js/) (currently offline)
107108- [GitHub mirror](https://github.com/lapo-luchini/asn1js)
109109+- [ChangeLog on GitHub](https://github.com/lapo-luchini/asn1js/blob/trunk/CHANGELOG.md)
108110- [Ohloh code stats](https://www.openhub.net/p/asn1js)
+289-79
asn1.js
···1313// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
1414// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15151616-import { Int10 } from './int10.js';
1716import { oids } from './oids.js';
18171918const
···2120 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)?)?$/,
2221 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)?)?$/,
2322 hexDigits = '0123456789ABCDEF',
2424- b64Safe = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
2323+ b64Std = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
2424+ b64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
2525 tableT61 = [
2626 ['', ''],
2727 ['AEIOUaeiou', 'รรรรรร รจรฌรฒรน'], // Grave
···4141 ['CDELNRSTZcdelnrstz', 'ฤฤฤฤฝลลล ลคลฝฤฤฤฤพลลลกลฅลพ'], // Caron
4242 ];
43434444+/**
4545+ * Truncates a string to a specified length and adds an ellipsis if needed.
4646+ * @param {string} str - The input string to truncate
4747+ * @param {number} len - The maximum length of the string
4848+ * @returns {string} The truncated string
4949+ */
4450function stringCut(str, len) {
4551 if (str.length > len)
4652 str = str.substring(0, len) + ellipsis;
4753 return str;
4854}
49555656+/**
5757+ * Checks if a string contains only printable characters (ASCII 32-126, plus tab, newline, carriage return)
5858+ * @param {string} s - The string to check
5959+ * @throws {Error} If an unprintable character is found
6060+ */
5061function checkPrintable(s) {
5162 let i, v;
5263 for (i = 0; i < s.length; ++i) {
···5667 }
5768}
58695959-/** Class to manage a stream of bytes, with a zero-copy approach.
6060- * It uses an existing array or binary string and advances a position index. */
6161-class Stream {
7070+/**
7171+ * Class to manage a stream of bytes, with a zero-copy approach.
7272+ * It uses an existing array or binary string and advances a position index.
7373+ */
7474+export class Stream {
62756376 /**
7777+ * Creates a new Stream object.
6478 * @param {Stream|array|string} enc data (will not be copied)
6579 * @param {?number} pos starting position (mandatory when `end` is not a Stream)
6680 */
···7488 }
7589 if (typeof this.pos != 'number')
7690 throw new Error('"pos" must be a numeric value');
9191+ // Set up the raw byte access function based on the type of data
7792 if (typeof this.enc == 'string')
7893 this.getRaw = pos => this.enc.charCodeAt(pos);
7994 else if (typeof this.enc[0] == 'number')
···8196 else
8297 throw new Error('"enc" must be a numeric array or a string');
8398 }
8484- /** Get the byte at current position (and increment it) or at a specified position (and avoid moving current position).
8585- * @param {?number} pos read position if specified, else current position (and increment it) */
9999+100100+ /**
101101+ * Get the byte at current position (and increment it) or at a specified position (and avoid moving current position).
102102+ * @param {?number} pos read position if specified, else current position (and increment it)
103103+ * @returns {number} The byte value at the specified position
104104+ */
86105 get(pos) {
87106 if (pos === undefined)
88107 pos = this.pos++;
···90109 throw new Error('Requesting byte offset ' + pos + ' on a stream of length ' + this.enc.length);
91110 return this.getRaw(pos);
92111 }
9393- /** Convert a single byte to an hexadcimal string (of length 2).
9494- * @param {number} b */
112112+113113+ /**
114114+ * Convert a single byte to a hexadecimal string (of length 2).
115115+ * @param {number} b - The byte to convert
116116+ * @returns {string} Hexadecimal representation of the byte
117117+ */
95118 static hexByte(b) {
96119 return hexDigits.charAt((b >> 4) & 0xF) + hexDigits.charAt(b & 0xF);
97120 }
9898- /** Hexadecimal dump of a specified region of the stream.
9999- * @param {number} start starting position (included)
100100- * @param {number} end ending position (excluded)
101101- * @param {string} type 'raw', 'byte' or 'dump' */
121121+122122+ /**
123123+ * Hexadecimal dump of a specified region of the stream.
124124+ * @param {number} start - starting position (included)
125125+ * @param {number} end - ending position (excluded)
126126+ * @param {string} type - 'raw', 'byte' or 'dump' (default)
127127+ * @returns {string} Hexadecimal representation of the data
128128+ */
102129 hexDump(start, end, type = 'dump') {
103130 let s = '';
104131 for (let i = start; i < end; ++i) {
···114141 }
115142 return s;
116143 }
117117- /** Base-64 dump of a specified region of the stream.
118118- * @param {number} start starting position (included)
119119- * @param {number} end ending position (excluded) */
120120- b64Dump(start, end) {
121121- let extra = (end - start) % 3,
122122- s = '',
144144+145145+ /**
146146+ * Base64url dump of a specified region of the stream (according to RFC 4648 section 5).
147147+ * @param {number} start - starting position (included)
148148+ * @param {number} end - ending position (excluded)
149149+ * @param {string} type - 'url' (default, section 5 without padding) or 'std' (section 4 with padding)
150150+ * @returns {string} Base64 encoded representation of the data
151151+ */
152152+ b64Dump(start, end, type = 'url') {
153153+ const b64 = type === 'url' ? b64URL : b64Std,
154154+ extra = (end - start) % 3;
155155+ let s = '',
123156 i, c;
124157 for (i = start; i + 2 < end; i += 3) {
125158 c = this.get(i) << 16 | this.get(i + 1) << 8 | this.get(i + 2);
126126- s += b64Safe.charAt(c >> 18 & 0x3F);
127127- s += b64Safe.charAt(c >> 12 & 0x3F);
128128- s += b64Safe.charAt(c >> 6 & 0x3F);
129129- s += b64Safe.charAt(c & 0x3F);
159159+ s += b64.charAt(c >> 18 & 0x3F);
160160+ s += b64.charAt(c >> 12 & 0x3F);
161161+ s += b64.charAt(c >> 6 & 0x3F);
162162+ s += b64.charAt(c & 0x3F);
130163 }
131164 if (extra > 0) {
132165 c = this.get(i) << 16;
133166 if (extra > 1) c |= this.get(i + 1) << 8;
134134- s += b64Safe.charAt(c >> 18 & 0x3F);
135135- s += b64Safe.charAt(c >> 12 & 0x3F);
136136- if (extra == 2) s += b64Safe.charAt(c >> 6 & 0x3F);
167167+ s += b64.charAt(c >> 18 & 0x3F);
168168+ s += b64.charAt(c >> 12 & 0x3F);
169169+ if (extra == 2) s += b64.charAt(c >> 6 & 0x3F);
170170+ if (b64 === b64Std) s += '==='.slice(0, 3 - extra);
137171 }
138172 return s;
139173 }
174174+175175+ /**
176176+ * Check if a region of the stream contains only ASCII characters (32-176)
177177+ * @param {number} start - starting position (included)
178178+ * @param {number} end - ending position (excluded)
179179+ * @returns {boolean} True if all characters are ASCII, false otherwise
180180+ */
140181 isASCII(start, end) {
141182 for (let i = start; i < end; ++i) {
142183 let c = this.get(i);
···145186 }
146187 return true;
147188 }
189189+190190+ /**
191191+ * Parse a region of the stream as an ISO string
192192+ * @param {number} start - starting position (included)
193193+ * @param {number} end - ending position (excluded)
194194+ * @param {number} maxLength - maximum length of the output string
195195+ * @returns {Object} Object with size and str properties
196196+ */
148197 parseStringISO(start, end, maxLength) {
149198 let s = '';
150199 for (let i = start; i < end; ++i)
151200 s += String.fromCharCode(this.get(i));
152201 return { size: s.length, str: stringCut(s, maxLength) };
153202 }
203203+204204+ /**
205205+ * Parse a region of the stream as a T.61 string
206206+ * @param {number} start - starting position (included)
207207+ * @param {number} end - ending position (excluded)
208208+ * @param {number} maxLength - maximum length of the output string
209209+ * @returns {Object} Object with size and str properties
210210+ */
154211 parseStringT61(start, end, maxLength) {
155212 // warning: this code is not very well tested so far
156213 function merge(c, d) {
157157- let t = tableT61[c - 0xC0];
158158- let i = t[0].indexOf(String.fromCharCode(d));
214214+ const t = tableT61[c - 0xC0];
215215+ const i = t[0].indexOf(String.fromCharCode(d));
159216 return (i < 0) ? '\0' : t[1].charAt(i);
160217 }
161218 let s = '', c;
···172229 }
173230 return { size: s.length, str: stringCut(s, maxLength) };
174231 }
232232+233233+ /**
234234+ * Parse a region of the stream as a UTF-8 string
235235+ * @param {number} start - starting position (included)
236236+ * @param {number} end - ending position (excluded)
237237+ * @param {number} maxLength - maximum length of the output string
238238+ * @returns {Object} Object with size and str properties
239239+ */
175240 parseStringUTF(start, end, maxLength) {
241241+ /**
242242+ * Helper function to process UTF-8 continuation bytes
243243+ * @param {number} c - The continuation byte
244244+ * @returns {number} The extracted data bits
245245+ */
176246 function ex(c) { // must be 10xxxxxx
177247 if ((c < 0x80) || (c >= 0xC0))
178248 throw new Error('Invalid UTF-8 continuation byte: ' + c);
179249 return (c & 0x3F);
180250 }
251251+ /**
252252+ * Helper function to convert a code point to a surrogate pair
253253+ * @param {number} cp - The code point to convert
254254+ * @returns {string} The surrogate pair as a string
255255+ */
181256 function surrogate(cp) {
182257 if (cp < 0x10000)
183258 throw new Error('UTF-8 overlong encoding, codepoint encoded in 4 bytes: ' + cp);
···187262 }
188263 let s = '';
189264 for (let i = start; i < end; ) {
190190- let c = this.get(i++);
265265+ const c = this.get(i++);
191266 if (c < 0x80) // 0xxxxxxx (7 bit)
192267 s += String.fromCharCode(c);
193268 else if (c < 0xC0)
···203278 }
204279 return { size: s.length, str: stringCut(s, maxLength) };
205280 }
281281+282282+ /**
283283+ * Parse a region of the stream as a BMP (Basic Multilingual Plane) string
284284+ * @param {number} start - starting position (included)
285285+ * @param {number} end - ending position (excluded)
286286+ * @param {number} maxLength - maximum length of the output string
287287+ * @returns {Object} Object with size and str properties
288288+ */
206289 parseStringBMP(start, end, maxLength) {
207290 let s = '', hi, lo;
208291 for (let i = start; i < end; ) {
···212295 }
213296 return { size: s.length, str: stringCut(s, maxLength) };
214297 }
298298+299299+ /**
300300+ * Parse a region of the stream as a time string
301301+ * @param {number} start - starting position (included)
302302+ * @param {number} end - ending position (excluded)
303303+ * @param {boolean} shortYear - Whether to parse as short year (2-digit)
304304+ * @returns {string} Formatted time string
305305+ */
215306 parseTime(start, end, shortYear) {
216307 let s = this.parseStringISO(start, end).str,
217308 m = (shortYear ? reTimeS : reTimeL).exec(s);
···239330 }
240331 return s;
241332 }
333333+334334+ /**
335335+ * Parse a region of the stream as an integer
336336+ * @param {number} start - starting position (included)
337337+ * @param {number} end - ending position (excluded)
338338+ * @returns {string} Formatted integer string
339339+ */
242340 parseInteger(start, end) {
243341 let v = this.get(start),
244244- neg = (v > 127),
245245- pad = neg ? 255 : 0,
246246- len,
247342 s = '';
343343+ const neg = (v > 127),
344344+ pad = neg ? 255 : 0;
248345 // skip unuseful bits (not allowed in DER)
249346 while (v == pad && ++start < end)
250347 v = this.get(start);
251251- len = end - start;
348348+ const len = end - start;
252349 if (len === 0)
253350 return neg ? '-1' : '0';
254351 // show bit length of huge integers
255352 if (len > 4) {
256256- s = v;
257257- len <<= 3;
258258- while (((s ^ pad) & 0x80) == 0) {
259259- s <<= 1;
260260- --len;
353353+ let v2 = v,
354354+ lenBit = len << 3;
355355+ while (((v2 ^ pad) & 0x80) == 0) {
356356+ v2 <<= 1;
357357+ --lenBit;
261358 }
262262- s = '(' + len + ' bit)\n';
359359+ s = '(' + lenBit + ' bit)\n';
263360 }
264361 // decode the integer
265362 if (neg) v = v - 256;
266266- let n = new Int10(v);
363363+ let n = BigInt(v);
267364 for (let i = start + 1; i < end; ++i)
268268- n.mulAdd(256, this.get(i));
269269- return s + n.toString();
365365+ n = (n << 8n) | BigInt(this.get(i));
366366+ return s + n;
270367 }
368368+369369+ /**
370370+ * Parse a region of the stream as a bit string.
371371+ * @param {number} start - starting position (included)
372372+ * @param {number} end - ending position (excluded)
373373+ * @param {number} maxLength - maximum length of the output string
374374+ * @returns {Object} Object with size and str properties
375375+ */
271376 parseBitString(start, end, maxLength) {
272272- let unusedBits = this.get(start);
377377+ const unusedBits = this.get(start);
273378 if (unusedBits > 7)
274379 throw new Error('Invalid BitString with unusedBits=' + unusedBits);
275275- let lenBit = ((end - start - 1) << 3) - unusedBits,
276276- s = '';
380380+ const lenBit = ((end - start - 1) << 3) - unusedBits;
381381+ let s = '';
277382 for (let i = start + 1; i < end; ++i) {
278383 let b = this.get(i),
279384 skip = (i == end - 1) ? unusedBits : 0;
···284389 }
285390 return { size: lenBit, str: s };
286391 }
392392+393393+ /**
394394+ * Parse a region of the stream as an octet string.
395395+ * @param {number} start - starting position (included)
396396+ * @param {number} end - ending position (excluded)
397397+ * @param {number} maxLength - maximum length of the output string
398398+ * @returns {Object} Object with size and str properties
399399+ */
287400 parseOctetString(start, end, maxLength) {
288288- let len = end - start,
289289- s;
290401 try {
291291- s = this.parseStringUTF(start, end, maxLength);
402402+ let s = this.parseStringUTF(start, end, maxLength);
292403 checkPrintable(s.str);
293404 return { size: end - start, str: s.str };
294294- } catch (e) {
295295- // ignore
405405+ } catch (ignore) {
406406+ // If UTF-8 parsing fails, fall back to hexadecimal dump
296407 }
408408+ const len = end - start;
297409 maxLength /= 2; // we work in bytes
298410 if (len > maxLength)
299411 end = start + maxLength;
300300- s = '';
412412+ let s = '';
301413 for (let i = start; i < end; ++i)
302414 s += Stream.hexByte(this.get(i));
303415 if (len > maxLength)
304416 s += ellipsis;
305417 return { size: len, str: s };
306418 }
419419+420420+ /**
421421+ * Parse a region of the stream as an OID (Object Identifier).
422422+ * @param {number} start - starting position (included)
423423+ * @param {number} end - ending position (excluded)
424424+ * @param {number} maxLength - maximum length of the output string
425425+ * @param {boolean} isRelative - Whether the OID is relative
426426+ * @returns {string} Formatted OID string
427427+ */
307428 parseOID(start, end, maxLength, isRelative) {
308429 let s = '',
309309- n = new Int10(),
430430+ n = 0n,
310431 bits = 0;
311432 for (let i = start; i < end; ++i) {
312433 let v = this.get(i);
313313- n.mulAdd(128, v & 0x7F);
434434+ // Shift bits and add the lower 7 bits of the byte
435435+ n = (n << 7n) | BigInt(v & 0x7F);
314436 bits += 7;
437437+ // If the most significant bit is 0, this is the last byte of the OID component
315438 if (!(v & 0x80)) { // finished
439439+ // If this is the first component, handle it specially
316440 if (s === '') {
317317- n = n.simplify();
318441 if (isRelative) {
319319- s = (n instanceof Int10) ? n.toString() : '' + n;
320320- } else if (n instanceof Int10) {
321321- n.sub(80);
322322- s = '2.' + n.toString();
442442+ s = n.toString();
323443 } else {
324324- let m = n < 80 ? n < 40 ? 0 : 1 : 2;
325325- s = m + '.' + (n - m * 40);
444444+ let m = n < 80 ? n < 40 ? 0n : 1n : 2n;
445445+ s = m + '.' + (n - m * 40n);
326446 }
327447 } else
328328- s += '.' + n.toString();
448448+ s += '.' + n;
329449 if (s.length > maxLength)
330450 return stringCut(s, maxLength);
331331- n = new Int10();
451451+ n = 0n;
332452 bits = 0;
333453 }
334454 }
335455 if (bits > 0)
336456 s += '.incomplete';
457457+ // If OIDs mapping is available and the OID is absolute, try to resolve it
337458 if (typeof oids === 'object' && !isRelative) {
338459 let oid = oids[s];
339460 if (oid) {
···344465 }
345466 return s;
346467 }
468468+469469+ /**
470470+ * Parse a region of the stream as a relative OID (Object Identifier).
471471+ * @param {number} start - starting position (included)
472472+ * @param {number} end - ending position (excluded)
473473+ * @param {number} maxLength - maximum length of the output string
474474+ * @returns {string} Formatted relative OID string
475475+ */
347476 parseRelativeOID(start, end, maxLength) {
348477 return this.parseOID(start, end, maxLength, true);
349478 }
···376505 this.tagConstructed = ((buf & 0x20) !== 0);
377506 this.tagNumber = buf & 0x1F;
378507 if (this.tagNumber == 0x1F) { // long tag
379379- let n = new Int10();
508508+ let n = 0n;
380509 do {
381510 buf = stream.get();
382382- n.mulAdd(128, buf & 0x7F);
511511+ n = (n << 7n) | BigInt(buf & 0x7F);
383512 } while (buf & 0x80);
384384- this.tagNumber = n.simplify();
513513+ this.tagNumber = n <= Number.MAX_SAFE_INTEGER ? Number(n) : n;
385514 }
386515 }
387516 isUniversal() {
···392521 }
393522}
394523524524+/**
525525+ * ASN1 class for parsing ASN.1 encoded data.
526526+ * Instances of this class represent an ASN.1 element and provides methods to parse and display its content.
527527+ */
395528export class ASN1 {
529529+ /**
530530+ * Creates an ASN1 parser object.
531531+ * @param {Stream} stream - The stream containing the ASN.1 data.
532532+ * @param {number} header - The header length.
533533+ * @param {number} length - The length of the data.
534534+ * @param {ASN1Tag} tag - The ASN.1 tag.
535535+ * @param {number} tagLen - The length of the tag.
536536+ * @param {Array} sub - The sub-elements.
537537+ */
396538 constructor(stream, header, length, tag, tagLen, sub) {
397539 if (!(tag instanceof ASN1Tag)) throw new Error('Invalid tag value.');
398540 this.stream = stream;
···402544 this.tagLen = tagLen;
403545 this.sub = sub;
404546 }
547547+548548+ /**
549549+ * Get the type name of the ASN.1 element.
550550+ * @returns {string} The type name.
551551+ */
405552 typeName() {
406553 switch (this.tag.tagClass) {
407554 case 0: // universal
···441588 case 3: return 'Private_' + this.tag.tagNumber.toString();
442589 }
443590 }
444444- /** A string preview of the content (intended for humans). */
591591+592592+ /**
593593+ * Get a string preview of the content (intended for humans).
594594+ * @param {number} maxLength - The maximum length of the content.
595595+ * @returns {string|null} The content preview or null if not supported.
596596+ */
445597 content(maxLength) {
446598 if (this.tag === undefined)
447599 return null;
448600 if (maxLength === undefined)
449601 maxLength = Infinity;
450450- let content = this.posContent(),
602602+ const content = this.posContent(),
451603 len = Math.abs(this.length);
452604 if (!this.tag.isUniversal()) {
453605 if (this.sub !== null)
···457609 }
458610 switch (this.tag.tagNumber) {
459611 case 0x01: // BOOLEAN
612612+ if (len != 1) return 'invalid length ' + len;
460613 return (this.stream.get(content) === 0) ? 'false' : 'true';
461614 case 0x02: // INTEGER
615615+ if (len < 1) return 'invalid length ' + len;
462616 return this.stream.parseInteger(content, content + len);
463617 case 0x03: { // BIT_STRING
464618 let d = recurse(this, 'parseBitString', maxLength);
···470624 }
471625 //case 0x05: // NULL
472626 case 0x06: // OBJECT_IDENTIFIER
627627+ if (len < 1) return 'invalid length ' + len; // pgut001's dumpasn1.c enforces a minimum lenght of 3
473628 return this.stream.parseOID(content, content + len, maxLength);
474629 //case 0x07: // ObjectDescriptor
475630 //case 0x08: // EXTERNAL
···506661 }
507662 return null;
508663 }
664664+665665+ /**
666666+ * Get a string representation of the ASN.1 element.
667667+ * @returns {string} The string representation.
668668+ */
509669 toString() {
510670 return this.typeName() + '@' + this.stream.pos + '[header:' + this.header + ',length:' + this.length + ',sub:' + ((this.sub === null) ? 'null' : this.sub.length) + ']';
511671 }
672672+673673+ /**
674674+ * Get a pretty string representation of the ASN.1 element.
675675+ * @param {string} indent - The indentation string.
676676+ * @returns {string} The pretty string representation.
677677+ */
512678 toPrettyString(indent) {
513679 if (indent === undefined) indent = '';
514680 let s = indent;
···539705 }
540706 return s;
541707 }
708708+709709+ /**
710710+ * Get the starting position of the element in the stream.
711711+ * @returns {number} The starting position.
712712+ */
542713 posStart() {
543714 return this.stream.pos;
544715 }
716716+717717+ /**
718718+ * Get the position of the content in the stream.
719719+ * @returns {number} The content position.
720720+ */
545721 posContent() {
546722 return this.stream.pos + this.header;
547723 }
724724+725725+ /**
726726+ * Get the ending position of the element in the stream.
727727+ * @returns {number} The ending position.
728728+ */
548729 posEnd() {
549730 return this.stream.pos + this.header + Math.abs(this.length);
550731 }
551551- /** Position of the length. */
732732+733733+ /**
734734+ * Get the position of the length in the stream.
735735+ * @returns {number} The length position.
736736+ */
552737 posLen() {
553738 return this.stream.pos + this.tagLen;
554739 }
555555- /** Hexadecimal dump of the node.
556556- * @param type 'raw', 'byte' or 'dump' */
740740+741741+ /**
742742+ * Get a hexadecimal dump of the node.
743743+ * @param {string} [type='raw'] - The dump type: 'raw', 'byte', or 'dump'.
744744+ * @returns {string} The hexadecimal dump.
745745+ */
557746 toHexString(type = 'raw') {
558747 return this.stream.hexDump(this.posStart(), this.posEnd(), type);
559748 }
560560- /** Base64 dump of the node. */
561561- toB64String() {
562562- return this.stream.b64Dump(this.posStart(), this.posEnd());
749749+750750+ /**
751751+ * Get a base64url dump of the node (according to RFC 4648 section 5).
752752+ * @param {string} [type='url'] - The dump type: 'url' (section 5 without padding) or 'std' (section 4 with padding).
753753+ * @returns {string} The base64 encoded representation.
754754+ */
755755+ toB64String(type = 'url') {
756756+ return this.stream.b64Dump(this.posStart(), this.posEnd(), type);
563757 }
758758+759759+ /**
760760+ * Decode the length field of an ASN.1 element.
761761+ * @param {Stream} stream - The stream to read from.
762762+ * @returns {number|null} The decoded length, or null for indefinite length.
763763+ * @throws {Error} If the length is invalid or exceeds 48 bits.
764764+ */
564765 static decodeLength(stream) {
565565- let buf = stream.get(),
766766+ const buf = stream.get(),
566767 len = buf & 0x7F;
567768 if (len == buf) // first bit was 0, short form
568769 return len;
569770 if (len === 0) // long form with length 0 is a special case
570771 return null; // undefined length
571571- if (len > 6) // no reason to use Int10, as it would be a huge buffer anyways
772772+ if (len > 6) // no reason to use BigInt, as it would be a huge buffer anyways
572773 throw new Error('Length over 48 bits not supported at position ' + (stream.pos - 1));
573573- buf = 0;
774774+ let value = 0;
574775 for (let i = 0; i < len; ++i)
575575- buf = (buf * 256) + stream.get();
576576- return buf;
776776+ value = (value << 8) | stream.get();
777777+ return value;
577778 }
779779+780780+ /**
781781+ * Decode an ASN.1 element from a stream.
782782+ * @param {Stream|array|string} stream - The input data.
783783+ * @param {number} [offset=0] - The offset to start decoding from.
784784+ * @param {Function} [type=ASN1] - The class to instantiate.
785785+ * @returns {ASN1} The decoded ASN.1 element.
786786+ * @throws {Error} If the decoding fails.
787787+ */
578788 static decode(stream, offset, type = ASN1) {
579789 if (!(type == ASN1 || type.prototype instanceof ASN1))
580790 throw new Error('Must pass a class that extends ASN1');
···632842 throw new Error('Unable to parse content: ' + e);
633843 }
634844 }
635635- } catch (e) {
845845+ } catch (ignore) {
636846 // but silently ignore when they don't
637847 sub = null;
638848 //DEBUG console.log('Could not decode structure at ' + start + ':', e);
···11-// Big integer base-10 printing library
22-// Copyright (c) 2008 Lapo Luchini <lapo@lapo.it>
33-44-// Permission to use, copy, modify, and/or distribute this software for any
55-// purpose with or without fee is hereby granted, provided that the above
66-// copyright notice and this permission notice appear in all copies.
77-//
88-// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
99-// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
1010-// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
1111-// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
1212-// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
1313-// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
1414-// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1515-1616-let max = 10000000000000; // biggest 10^n integer that can still fit 2^53 when multiplied by 256
1717-1818-export class Int10 {
1919- /**
2020- * Arbitrary length base-10 value.
2121- * @param {number} value - Optional initial value (will be 0 otherwise).
2222- */
2323- constructor(value) {
2424- this.buf = [+value || 0];
2525- }
2626-2727- /**
2828- * Multiply value by m and add c.
2929- * @param {number} m - multiplier, must be < =256
3030- * @param {number} c - value to add
3131- */
3232- mulAdd(m, c) {
3333- // assert(m <= 256)
3434- let b = this.buf,
3535- l = b.length,
3636- i, t;
3737- for (i = 0; i < l; ++i) {
3838- t = b[i] * m + c;
3939- if (t < max)
4040- c = 0;
4141- else {
4242- c = 0|(t / max);
4343- t -= c * max;
4444- }
4545- b[i] = t;
4646- }
4747- if (c > 0)
4848- b[i] = c;
4949- }
5050-5151- /**
5252- * Subtract value.
5353- * @param {number} c - value to subtract
5454- */
5555- sub(c) {
5656- let b = this.buf,
5757- l = b.length,
5858- i, t;
5959- for (i = 0; i < l; ++i) {
6060- t = b[i] - c;
6161- if (t < 0) {
6262- t += max;
6363- c = 1;
6464- } else
6565- c = 0;
6666- b[i] = t;
6767- }
6868- while (b[b.length - 1] === 0)
6969- b.pop();
7070- }
7171-7272- /**
7373- * Convert to decimal string representation.
7474- * @param {*} base - optional value, only value accepted is 10
7575- */
7676- toString(base) {
7777- if ((base || 10) != 10)
7878- throw 'only base 10 is supported';
7979- let b = this.buf,
8080- s = b[b.length - 1].toString();
8181- for (let i = b.length - 2; i >= 0; --i)
8282- s += (max + b[i]).toString().substring(1);
8383- return s;
8484- }
8585-8686- /**
8787- * Convert to Number value representation.
8888- * Will probably overflow 2^53 and thus become approximate.
8989- */
9090- valueOf() {
9191- let b = this.buf,
9292- v = 0;
9393- for (let i = b.length - 1; i >= 0; --i)
9494- v = v * max + b[i];
9595- return v;
9696- }
9797-9898- /**
9999- * Return value as a simple Number (if it is <= 10000000000000), or return this.
100100- */
101101- simplify() {
102102- let b = this.buf;
103103- return (b.length == 1) ? b[0] : this;
104104- }
105105-106106-}