JavaScript generic ASN.1 parser (mirror)
at github-56 2.6 kB view raw
1// Hex JavaScript decoder 2// Copyright (c) 2008-2022 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(typeof define != 'undefined' ? define : function (factory) { 'use strict'; 17 if (typeof module == 'object') module.exports = factory(); 18 else window.hex = factory(); 19})(function () { 20"use strict"; 21 22var Hex = {}, 23 decoder, // populated on first usage 24 haveU8 = (typeof Uint8Array == 'function'); 25 26/** 27 * Decodes an hexadecimal value. 28 * @param {string|Array|Uint8Array} a - a string representing hexadecimal data, or an array representation of its charcodes 29 */ 30Hex.decode = function(a) { 31 var isString = (typeof a == 'string'); 32 var i; 33 if (decoder === undefined) { 34 var hex = "0123456789ABCDEF", 35 ignore = " \f\n\r\t\u00A0\u2028\u2029"; 36 decoder = []; 37 for (i = 0; i < 16; ++i) 38 decoder[hex.charCodeAt(i)] = i; 39 hex = hex.toLowerCase(); 40 for (i = 10; i < 16; ++i) 41 decoder[hex.charCodeAt(i)] = i; 42 for (i = 0; i < ignore.length; ++i) 43 decoder[ignore.charCodeAt(i)] = -1; 44 } 45 var out = haveU8 ? new Uint8Array(a.length >> 1) : [], 46 bits = 0, 47 char_count = 0, 48 len = 0; 49 for (i = 0; i < a.length; ++i) { 50 var c = isString ? a.charCodeAt(i) : a[i]; 51 c = decoder[c]; 52 if (c == -1) 53 continue; 54 if (c === undefined) 55 throw 'Illegal character at offset ' + i; 56 bits |= c; 57 if (++char_count >= 2) { 58 out[len++] = bits; 59 bits = 0; 60 char_count = 0; 61 } else { 62 bits <<= 4; 63 } 64 } 65 if (char_count) 66 throw "Hex encoding incomplete: 4 bits missing"; 67 if (haveU8 && out.length > len) // in case it was originally longer because of ignored characters 68 out = out.subarray(0, len); 69 return out; 70}; 71 72return Hex; 73 74});