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