UNPKG

sm-crypto-v2

Version:
1,504 lines 150 kB
"use strict"; function _array_like_to_array(arr, len) { if (len == null || len > arr.length) len = arr.length; for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i]; return arr2; } function _array_with_holes(arr) { if (Array.isArray(arr)) return arr; } function _array_without_holes(arr) { if (Array.isArray(arr)) return _array_like_to_array(arr); } function _assert_this_initialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _async_to_generator(fn) { return function() { var self = this, args = arguments; return new Promise(function(resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _class_call_check(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _construct(Parent, args, Class) { if (_is_native_reflect_construct()) { _construct = Reflect.construct; } else { _construct = function construct(Parent, args, Class) { var a = [ null ]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _set_prototype_of(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _defineProperties(target, props) { for(var i = 0; i < props.length; i++){ var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _create_class(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _define_property(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _get_prototype_of(o) { _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _get_prototype_of(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _set_prototype_of(subClass, superClass); } function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } } function _is_native_function(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _iterable_to_array(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _iterable_to_array_limit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){ _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally{ try { if (!_n && _i["return"] != null) _i["return"](); } finally{ if (_d) throw _e; } } return _arr; } function _non_iterable_rest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _non_iterable_spread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _object_spread(target) { for(var i = 1; i < arguments.length; i++){ var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === "function") { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function(key) { _define_property(target, key, source[key]); }); } return target; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function(sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _object_spread_props(target, source) { source = source != null ? source : {}; if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function(key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _possible_constructor_return(self, call) { if (call && (_type_of(call) === "object" || typeof call === "function")) { return call; } return _assert_this_initialized(self); } function _set_prototype_of(o, p) { _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _set_prototype_of(o, p); } function _sliced_to_array(arr, i) { return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest(); } function _to_consumable_array(arr) { return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread(); } function _type_of(obj) { "@swc/helpers - typeof"; return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; } function _unsupported_iterable_to_array(o, minLen) { if (!o) return; if (typeof o === "string") return _array_like_to_array(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen); } function _wrap_native_super(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrap_native_super = function wrapNativeSuper(Class) { if (Class === null || !_is_native_function(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _get_prototype_of(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _set_prototype_of(Wrapper, Class); }; return _wrap_native_super(Class); } function _is_native_reflect_construct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})); return true; } catch (e) { return false; } } function _create_super(Derived) { var hasNativeReflectConstruct = _is_native_reflect_construct(); return function _createSuperInternal() { var Super = _get_prototype_of(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _get_prototype_of(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possible_constructor_return(this, result); }; } function _ts_generator(thisArg, body) { var f, y, t, g, _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function(v) { return step([ n, v ]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while(_)try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [ op[0] & 2, t.value ]; switch(op[0]){ case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [ 0 ]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [ 6, e ]; y = 0; } finally{ f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __defNormalProp = function(obj, key, value) { return key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value; }; var __export = function(target, all) { for(var name in all)__defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = function(to, from, except, desc) { if (from && typeof from === "object" || typeof from === "function") { var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined; try { var _loop = function() { var key = _step.value; if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: function() { return from[key]; }, enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); }; for(var _iterator = __getOwnPropNames(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop(); } catch (err) { _didIteratorError = true; _iteratorError = err; } finally{ try { if (!_iteratorNormalCompletion && _iterator.return != null) { _iterator.return(); } } finally{ if (_didIteratorError) { throw _iteratorError; } } } } return to; }; var __toESM = function(mod2, isNodeMode, target) { return target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(// If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target, mod2); }; var __toCommonJS = function(mod2) { return __copyProps(__defProp({}, "__esModule", { value: true }), mod2); }; var __publicField = function(obj, key, value) { __defNormalProp(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value); return value; }; // src/index.ts var src_exports = {}; __export(src_exports, { kdf: function() { return kdf; }, sm2: function() { return sm2_exports; }, sm3: function() { return sm32; }, sm4: function() { return sm4_exports; } }); module.exports = __toCommonJS(src_exports); // src/sm2/index.ts var sm2_exports = {}; __export(sm2_exports, { EmptyArray: function() { return EmptyArray; }, arrayToHex: function() { return arrayToHex; }, arrayToUtf8: function() { return arrayToUtf8; }, calculateSharedKey: function() { return calculateSharedKey; }, comparePublicKeyHex: function() { return comparePublicKeyHex; }, compressPublicKeyHex: function() { return compressPublicKeyHex; }, doDecrypt: function() { return doDecrypt; }, doEncrypt: function() { return doEncrypt; }, doSignature: function() { return doSignature; }, doVerifySignature: function() { return doVerifySignature; }, ecdh: function() { return getSharedSecret; }, generateKeyPairHex: function() { return generateKeyPairHex; }, getHash: function() { return getHash; }, getPoint: function() { return getPoint; }, getPublicKeyFromPrivateKey: function() { return getPublicKeyFromPrivateKey; }, getZ: function() { return getZ; }, hexToArray: function() { return hexToArray; }, initRNGPool: function() { return initRNGPool; }, leftPad: function() { return leftPad; }, precomputePublicKey: function() { return precomputePublicKey; }, utf8ToHex: function() { return utf8ToHex; }, verifyPublicKey: function() { return verifyPublicKey; } }); // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/abstract/utils.js var utils_exports = {}; __export(utils_exports, { bitGet: function() { return bitGet; }, bitLen: function() { return bitLen; }, bitMask: function() { return bitMask; }, bitSet: function() { return bitSet; }, bytesToHex: function() { return bytesToHex; }, bytesToNumberBE: function() { return bytesToNumberBE; }, bytesToNumberLE: function() { return bytesToNumberLE; }, concatBytes: function() { return concatBytes; }, createHmacDrbg: function() { return createHmacDrbg; }, ensureBytes: function() { return ensureBytes; }, equalBytes: function() { return equalBytes; }, hexToBytes: function() { return hexToBytes; }, hexToNumber: function() { return hexToNumber; }, numberToBytesBE: function() { return numberToBytesBE; }, numberToBytesLE: function() { return numberToBytesLE; }, numberToHexUnpadded: function() { return numberToHexUnpadded; }, numberToVarBytesBE: function() { return numberToVarBytesBE; }, utf8ToBytes: function() { return utf8ToBytes; }, validateObject: function() { return validateObject; } }); var _0n = BigInt(0); var _1n = BigInt(1); var _2n = BigInt(2); var u8a = function(a) { return _instanceof(a, Uint8Array); }; var hexes = Array.from({ length: 256 }, function(v, i) { return i.toString(16).padStart(2, "0"); }); function bytesToHex(bytes) { if (!u8a(bytes)) throw new Error("Uint8Array expected"); var hex = ""; for(var i = 0; i < bytes.length; i++){ hex += hexes[bytes[i]]; } return hex; } function numberToHexUnpadded(num) { var hex = num.toString(16); return hex.length & 1 ? "0".concat(hex) : hex; } function hexToNumber(hex) { if (typeof hex !== "string") throw new Error("hex string expected, got " + (typeof hex === "undefined" ? "undefined" : _type_of(hex))); return BigInt(hex === "" ? "0" : "0x".concat(hex)); } function hexToBytes(hex) { if (typeof hex !== "string") throw new Error("hex string expected, got " + (typeof hex === "undefined" ? "undefined" : _type_of(hex))); var len = hex.length; if (len % 2) throw new Error("padded hex string expected, got unpadded hex of length " + len); var array = new Uint8Array(len / 2); for(var i = 0; i < array.length; i++){ var j = i * 2; var hexByte = hex.slice(j, j + 2); var byte = Number.parseInt(hexByte, 16); if (Number.isNaN(byte) || byte < 0) throw new Error("Invalid byte sequence"); array[i] = byte; } return array; } function bytesToNumberBE(bytes) { return hexToNumber(bytesToHex(bytes)); } function bytesToNumberLE(bytes) { if (!u8a(bytes)) throw new Error("Uint8Array expected"); return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); } function numberToBytesBE(n, len) { return hexToBytes(n.toString(16).padStart(len * 2, "0")); } function numberToBytesLE(n, len) { return numberToBytesBE(n, len).reverse(); } function numberToVarBytesBE(n) { return hexToBytes(numberToHexUnpadded(n)); } function ensureBytes(title, hex, expectedLength) { var res; if (typeof hex === "string") { try { res = hexToBytes(hex); } catch (e) { throw new Error("".concat(title, ' must be valid hex string, got "').concat(hex, '". Cause: ').concat(e)); } } else if (u8a(hex)) { res = Uint8Array.from(hex); } else { throw new Error("".concat(title, " must be hex string or Uint8Array")); } var len = res.length; if (typeof expectedLength === "number" && len !== expectedLength) throw new Error("".concat(title, " expected ").concat(expectedLength, " bytes, got ").concat(len)); return res; } function concatBytes() { for(var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++){ arrays[_key] = arguments[_key]; } var r = new Uint8Array(arrays.reduce(function(sum, a) { return sum + a.length; }, 0)); var pad = 0; arrays.forEach(function(a) { if (!u8a(a)) throw new Error("Uint8Array expected"); r.set(a, pad); pad += a.length; }); return r; } function equalBytes(b1, b2) { if (b1.length !== b2.length) return false; for(var i = 0; i < b1.length; i++)if (b1[i] !== b2[i]) return false; return true; } function utf8ToBytes(str) { if (typeof str !== "string") throw new Error("utf8ToBytes expected string, got ".concat(typeof str === "undefined" ? "undefined" : _type_of(str))); return new Uint8Array(new TextEncoder().encode(str)); } function bitLen(n) { var len; for(len = 0; n > _0n; n >>= _1n, len += 1); return len; } function bitGet(n, pos) { return n >> BigInt(pos) & _1n; } var bitSet = function(n, pos, value) { return n | (value ? _1n : _0n) << BigInt(pos); }; var bitMask = function(n) { return (_2n << BigInt(n - 1)) - _1n; }; var u8n = function(data) { return new Uint8Array(data); }; var u8fr = function(arr) { return Uint8Array.from(arr); }; function createHmacDrbg(hashLen, qByteLen, hmacFn) { if (typeof hashLen !== "number" || hashLen < 2) throw new Error("hashLen must be a number"); if (typeof qByteLen !== "number" || qByteLen < 2) throw new Error("qByteLen must be a number"); if (typeof hmacFn !== "function") throw new Error("hmacFn must be a function"); var v = u8n(hashLen); var k = u8n(hashLen); var i = 0; var reset = function() { v.fill(1); k.fill(0); i = 0; }; var h = function() { for(var _len = arguments.length, b = new Array(_len), _key = 0; _key < _len; _key++){ b[_key] = arguments[_key]; } return hmacFn.apply(void 0, [ k, v ].concat(_to_consumable_array(b))); }; var reseed = function() { var seed = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : u8n(); k = h(u8fr([ 0 ]), seed); v = h(); if (seed.length === 0) return; k = h(u8fr([ 1 ]), seed); v = h(); }; var gen = function() { if (i++ >= 1e3) throw new Error("drbg: tried 1000 values"); var len = 0; var out = []; while(len < qByteLen){ v = h(); var sl = v.slice(); out.push(sl); len += v.length; } return concatBytes.apply(void 0, _to_consumable_array(out)); }; var genUntil = function(seed, pred) { reset(); reseed(seed); var res = void 0; while(!(res = pred(gen())))reseed(); reset(); return res; }; return genUntil; } var validatorFns = { bigint: function(val) { return (typeof val === "undefined" ? "undefined" : _type_of(val)) === "bigint"; }, function: function(val) { return typeof val === "function"; }, boolean: function(val) { return typeof val === "boolean"; }, string: function(val) { return typeof val === "string"; }, isSafeInteger: function(val) { return Number.isSafeInteger(val); }, array: function(val) { return Array.isArray(val); }, field: function(val, object) { return object.Fp.isValid(val); }, hash: function(val) { return typeof val === "function" && Number.isSafeInteger(val.outputLen); } }; function validateObject(object, validators) { var optValidators = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; var checkField = function(fieldName, type, isOptional) { var checkVal = validatorFns[type]; if (typeof checkVal !== "function") throw new Error('Invalid validator "'.concat(type, '", expected function')); var val = object[fieldName]; if (isOptional && val === void 0) return; if (!checkVal(val, object)) { throw new Error("Invalid param ".concat(String(fieldName), "=").concat(val, " (").concat(typeof val === "undefined" ? "undefined" : _type_of(val), "), expected ").concat(type)); } }; var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined; try { for(var _iterator = Object.entries(validators)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){ var _step_value = _sliced_to_array(_step.value, 2), fieldName = _step_value[0], type = _step_value[1]; checkField(fieldName, type, false); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally{ try { if (!_iteratorNormalCompletion && _iterator.return != null) { _iterator.return(); } } finally{ if (_didIteratorError) { throw _iteratorError; } } } var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined; try { for(var _iterator1 = Object.entries(optValidators)[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){ var _step_value1 = _sliced_to_array(_step1.value, 2), fieldName1 = _step_value1[0], type1 = _step_value1[1]; checkField(fieldName1, type1, true); } } catch (err) { _didIteratorError1 = true; _iteratorError1 = err; } finally{ try { if (!_iteratorNormalCompletion1 && _iterator1.return != null) { _iterator1.return(); } } finally{ if (_didIteratorError1) { throw _iteratorError1; } } } return object; } // src/sm2/bn.ts var ZERO = BigInt(0); var ONE = BigInt(1); var TWO = BigInt(2); var THREE = BigInt(3); // src/sm2/asn1.ts function bigintToValue(bigint) { var h = bigint.toString(16); if (h[0] !== "-") { if (h.length % 2 === 1) h = "0" + h; else if (!h.match(/^[0-7]/)) h = "00" + h; } else { h = h.substring(1); var len = h.length; if (len % 2 === 1) len += 1; else if (!h.match(/^[0-7]/)) len += 2; var maskString = ""; for(var i = 0; i < len; i++)maskString += "f"; var mask = hexToNumber(maskString); var output = (mask ^ bigint) + ONE; h = output.toString(16).replace(/^-/, ""); } return h; } var ASN1Object = /*#__PURE__*/ function() { function ASN1Object() { var tlv = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : null, t = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "00", l = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "00", v = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : ""; _class_call_check(this, ASN1Object); this.tlv = tlv; this.t = t; this.l = l; this.v = v; } _create_class(ASN1Object, [ { /** * 获取 der 编码比特流16进制串 */ key: "getEncodedHex", value: function getEncodedHex() { if (!this.tlv) { this.v = this.getValue(); this.l = this.getLength(); this.tlv = this.t + this.l + this.v; } return this.tlv; } }, { key: "getLength", value: function getLength() { var n = this.v.length / 2; var nHex = n.toString(16); if (nHex.length % 2 === 1) nHex = "0" + nHex; if (n < 128) { return nHex; } else { var head = 128 + nHex.length / 2; return head.toString(16) + nHex; } } }, { key: "getValue", value: function getValue() { return ""; } } ]); return ASN1Object; }(); var DERInteger = /*#__PURE__*/ function(ASN1Object) { _inherits(DERInteger, ASN1Object); var _super = _create_super(DERInteger); function DERInteger(bigint) { _class_call_check(this, DERInteger); var _this; _this = _super.call(this); _this.t = "02"; if (bigint) _this.v = bigintToValue(bigint); return _this; } _create_class(DERInteger, [ { key: "getValue", value: function getValue() { return this.v; } } ]); return DERInteger; }(ASN1Object); var DEROctetString = /*#__PURE__*/ function(ASN1Object) { _inherits(DEROctetString, ASN1Object); var _super = _create_super(DEROctetString); function DEROctetString(s) { _class_call_check(this, DEROctetString); var _this; _this = _super.call(this); _this.s = s; __publicField(_assert_this_initialized(_this), "hV", ""); _this.t = "04"; if (s) _this.v = s.toLowerCase(); return _this; } _create_class(DEROctetString, [ { key: "getValue", value: function getValue() { return this.v; } } ]); return DEROctetString; }(ASN1Object); var DERSequence = /*#__PURE__*/ function(ASN1Object) { _inherits(DERSequence, ASN1Object); var _super = _create_super(DERSequence); function DERSequence(asn1Array) { _class_call_check(this, DERSequence); var _this; _this = _super.call(this); _this.asn1Array = asn1Array; __publicField(_assert_this_initialized(_this), "t", "30"); return _this; } _create_class(DERSequence, [ { key: "getValue", value: function getValue() { this.v = this.asn1Array.map(function(asn1Object) { return asn1Object.getEncodedHex(); }).join(""); return this.v; } } ]); return DERSequence; }(ASN1Object); function getLenOfL(str, start) { if (+str[start + 2] < 8) return 1; var encoded = str.slice(start + 2, start + 6); var headHex = encoded.slice(0, 2); var head = parseInt(headHex, 16); var nHexLength = (head - 128) * 2; return nHexLength; } function getL(str, start) { var len = getLenOfL(str, start); var l = str.substring(start + 2, start + 2 + len * 2); if (!l) return -1; var bigint = +l[0] < 8 ? hexToNumber(l) : hexToNumber(l.substring(2)); return +bigint.toString(); } function getStartOfV(str, start) { var len = getLenOfL(str, start); return start + (len + 1) * 2; } function encodeDer(r, s) { var derR = new DERInteger(r); var derS = new DERInteger(s); var derSeq = new DERSequence([ derR, derS ]); return derSeq.getEncodedHex(); } function encodeEnc(x2, y, hash, cipher) { var derX = new DERInteger(x2); var derY = new DERInteger(y); var derHash = new DEROctetString(hash); var derCipher = new DEROctetString(cipher); var derSeq = new DERSequence([ derX, derY, derHash, derCipher ]); return derSeq.getEncodedHex(); } function decodeDer(input) { var start = getStartOfV(input, 0); var vIndexR = getStartOfV(input, start); var lR = getL(input, start); var vR = input.substring(vIndexR, vIndexR + lR * 2); var nextStart = vIndexR + vR.length; var vIndexS = getStartOfV(input, nextStart); var lS = getL(input, nextStart); var vS = input.substring(vIndexS, vIndexS + lS * 2); var r = hexToNumber(vR); var s = hexToNumber(vS); return { r: r, s: s }; } function decodeEnc(input) { var extractSequence = function extractSequence(input2, start2) { var vIndex = getStartOfV(input2, start2); var length = getL(input2, start2); var value = input2.substring(vIndex, vIndex + length * 2); var nextStart = vIndex + value.length; return { value: value, nextStart: nextStart }; }; var start = getStartOfV(input, 0); var _extractSequence = extractSequence(input, start), vR = _extractSequence.value, startS = _extractSequence.nextStart; var _extractSequence1 = extractSequence(input, startS), vS = _extractSequence1.value, startHash = _extractSequence1.nextStart; var _extractSequence2 = extractSequence(input, startHash), hash = _extractSequence2.value, startCipher = _extractSequence2.nextStart; var _extractSequence3 = extractSequence(input, startCipher), cipher = _extractSequence3.value; var x2 = hexToNumber(vR); var y = hexToNumber(vS); return { x: x2, y: y, hash: hash, cipher: cipher }; } // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/abstract/modular.js var _0n2 = BigInt(0); var _1n2 = BigInt(1); var _2n2 = BigInt(2); var _3n = BigInt(3); var _4n = BigInt(4); var _5n = BigInt(5); var _8n = BigInt(8); var _9n = BigInt(9); var _16n = BigInt(16); function mod(a, b) { var result = a % b; return result >= _0n2 ? result : b + result; } function pow(num, power, modulo) { if (modulo <= _0n2 || power < _0n2) throw new Error("Expected power/modulo > 0"); if (modulo === _1n2) return _0n2; var res = _1n2; while(power > _0n2){ if (power & _1n2) res = res * num % modulo; num = num * num % modulo; power >>= _1n2; } return res; } function invert(number, modulo) { if (number === _0n2 || modulo <= _0n2) { throw new Error("invert: expected positive integers, got n=".concat(number, " mod=").concat(modulo)); } var a = mod(number, modulo); var b = modulo; var x2 = _0n2, y = _1n2, u = _1n2, v = _0n2; while(a !== _0n2){ var q = b / a; var r = b % a; var m = x2 - u * q; var n = y - v * q; b = a, a = r, x2 = u, y = v, u = m, v = n; } var gcd = b; if (gcd !== _1n2) throw new Error("invert: does not exist"); return mod(x2, modulo); } function tonelliShanks(P) { var legendreC = (P - _1n2) / _2n2; var Q, S, Z; for(Q = P - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++); for(Z = _2n2; Z < P && pow(Z, legendreC, P) !== P - _1n2; Z++); if (S === 1) { var p1div4 = (P + _1n2) / _4n; return function tonelliFast(Fp, n) { var root = Fp.pow(n, p1div4); if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root"); return root; }; } var Q1div2 = (Q + _1n2) / _2n2; return function tonelliSlow(Fp, n) { if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error("Cannot find square root"); var r = S; var g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); var x2 = Fp.pow(n, Q1div2); var b = Fp.pow(n, Q); while(!Fp.eql(b, Fp.ONE)){ if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; var m = 1; for(var t2 = Fp.sqr(b); m < r; m++){ if (Fp.eql(t2, Fp.ONE)) break; t2 = Fp.sqr(t2); } var ge = Fp.pow(g, _1n2 << BigInt(r - m - 1)); g = Fp.sqr(ge); x2 = Fp.mul(x2, ge); b = Fp.mul(b, g); r = m; } return x2; }; } function FpSqrt(P) { if (P % _4n === _3n) { var p1div4 = (P + _1n2) / _4n; return function sqrt3mod4(Fp, n) { var root = Fp.pow(n, p1div4); if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root"); return root; }; } if (P % _8n === _5n) { var c1 = (P - _5n) / _8n; return function sqrt5mod8(Fp, n) { var n2 = Fp.mul(n, _2n2); var v = Fp.pow(n2, c1); var nv = Fp.mul(n, v); var i = Fp.mul(Fp.mul(nv, _2n2), v); var root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root"); return root; }; } if (P % _16n === _9n) {} return tonelliShanks(P); } var FIELD_FIELDS = [ "create", "isValid", "is0", "neg", "inv", "sqrt", "sqr", "eql", "add", "sub", "mul", "pow", "div", "addN", "subN", "mulN", "sqrN" ]; function validateField(field2) { var initial = { ORDER: "bigint", MASK: "bigint", BYTES: "isSafeInteger", BITS: "isSafeInteger" }; var opts = FIELD_FIELDS.reduce(function(map, val) { map[val] = "function"; return map; }, initial); return validateObject(field2, opts); } function FpPow(f, num, power) { if (power < _0n2) throw new Error("Expected power > 0"); if (power === _0n2) return f.ONE; if (power === _1n2) return num; var p = f.ONE; var d = num; while(power > _0n2){ if (power & _1n2) p = f.mul(p, d); d = f.sqr(d); power >>= _1n2; } return p; } function FpInvertBatch(f, nums) { var tmp2 = new Array(nums.length); var lastMultiplied = nums.reduce(function(acc, num, i) { if (f.is0(num)) return acc; tmp2[i] = acc; return f.mul(acc, num); }, f.ONE); var inverted = f.inv(lastMultiplied); nums.reduceRight(function(acc, num, i) { if (f.is0(num)) return acc; tmp2[i] = f.mul(acc, tmp2[i]); return f.mul(acc, num); }, inverted); return tmp2; } function nLength(n, nBitLength) { var _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; var nByteLength = Math.ceil(_nBitLength / 8); return { nBitLength: _nBitLength, nByteLength: nByteLength }; } function Field(ORDER, bitLen2) { var isLE3 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false, redef = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {}; if (ORDER <= _0n2) throw new Error("Expected Fp ORDER > 0, got ".concat(ORDER)); var _nLength = nLength(ORDER, bitLen2), BITS = _nLength.nBitLength, BYTES = _nLength.nByteLength; if (BYTES > 2048) throw new Error("Field lengths over 2048 bytes are not supported"); var sqrtP = FpSqrt(ORDER); var f = Object.freeze({ ORDER: ORDER, BITS: BITS, BYTES: BYTES, MASK: bitMask(BITS), ZERO: _0n2, ONE: _1n2, create: function(num) { return mod(num, ORDER); }, isValid: function(num) { if ((typeof num === "undefined" ? "undefined" : _type_of(num)) !== "bigint") throw new Error("Invalid field element: expected bigint, got ".concat(typeof num === "undefined" ? "undefined" : _type_of(num))); return _0n2 <= num && num < ORDER; }, is0: function(num) { return num === _0n2; }, isOdd: function(num) { return (num & _1n2) === _1n2; }, neg: function(num) { return mod(-num, ORDER); }, eql: function(lhs, rhs) { return lhs === rhs; }, sqr: function(num) { return mod(num * num, ORDER); }, add: function(lhs, rhs) { return mod(lhs + rhs, ORDER); }, sub: function(lhs, rhs) { return mod(lhs - rhs, ORDER); }, mul: function(lhs, rhs) { return mod(lhs * rhs, ORDER); }, pow: function(num, power) { return FpPow(f, num, power); }, div: function(lhs, rhs) { return mod(lhs * invert(rhs, ORDER), ORDER); }, // Same as above, but doesn't normalize sqrN: function(num) { return num * num; }, addN: function(lhs, rhs) { return lhs + rhs; }, subN: function(lhs, rhs) { return lhs - rhs; }, mulN: function(lhs, rhs) { return lhs * rhs; }, inv: function(num) { return invert(num, ORDER); }, sqrt: redef.sqrt || function(n) { return sqrtP(f, n); }, invertBatch: function(lst) { return FpInvertBatch(f, lst); }, // TODO: do we really need constant cmov? // We don't have const-time bigints anyway, so probably will be not very useful cmov: function(a, b, c) { return c ? b : a; }, toBytes: function(num) { return isLE3 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES); }, fromBytes: function(bytes) { if (bytes.length !== BYTES) throw new Error("Fp.fromBytes: expected ".concat(BYTES, ", got ").concat(bytes.length)); return isLE3 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); } }); return Object.freeze(f); } function hashToPrivateScalar(hash, groupOrder) { var isLE3 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false; hash = ensureBytes("privateHash", hash); var hashLen = hash.length; var minLen = nLength(groupOrder).nByteLength + 8; if (minLen < 24 || hashLen < minLen || hashLen > 1024) throw new Error("hashToPrivateScalar: expected ".concat(minLen, "-1024 bytes of input, got ").concat(hashLen)); var num = isLE3 ? bytesToNumberLE(hash) : bytesToNumberBE(hash); return mod(num, groupOrder - _1n2) + _1n2; } // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/abstract/curve.js var _0n3 = BigInt(0); var _1n3 = BigInt(1); function wNAF(c, bits) { var constTimeNegate = function(condition, item) { var neg = item.negate(); return condition ? neg : item; }; var opts = function(W) { var windows = Math.ceil(bits / W) + 1; var windowSize = Math.pow(2, W - 1); return { windows: windows, windowSize: windowSize }; }; return { constTimeNegate: constTimeNegate, // non-const time multiplication ladder unsafeLadder: function unsafeLadder(elm, n) { var p = c.ZERO; var d = elm; while(n > _0n3){ if (n & _1n3) p = p.add(d); d = d.double(); n >>= _1n3; } return p; }, /** * Creates a wNAF precomputation window. Used for caching. * Default window size is set by `utils.precompute()` and is equal to 8. * Number of precomputed points depends on the curve size: * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: * - 𝑊 is the window size * - 𝑛 is the bitlength of the curve order. * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. * @returns precomputed point tables flattened to a single array */ precomputeWindow: function precomputeWindow(elm, W) { var _opts = opts(W), windows = _opts.windows, windowSize = _opts.windowSize; var points = []; var p = elm; var base = p; for(var window = 0; window < windows; window++){ base = p; points.push(base); for(var i = 1; i < windowSize; i++){ base = base.add(p); points.push(base); } p = base.double(); } return points; }, /** * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. * @param W window size * @param precomputes precomputed tables * @param n scalar (we don't check here, but should be less than curve order) * @returns real and fake (for const-time) points */ wNAF: function wNAF(W, precomputes, n) { var _opts = opts(W), windows = _opts.windows, windowSize = _opts.windowSize; var p = c.ZERO; var f = c.BASE; var mask = BigInt(Math.pow(2, W) - 1); var maxNumber = Math.pow(2, W); var shiftBy = BigInt(W); for(var window = 0; window < windows; window++){ var offset = window * windowSize; var wbits = Number(n & mask); n >>= shiftBy; if (wbits > windowSize) { wbits -= maxNumber; n += _1n3; } var offset1 = offset; var offset2 = offset + Math.abs(wbits) - 1; var cond1 = window % 2 !== 0; var cond2 = wbits < 0; if (wbits === 0) { f = f.add(constTimeNegate(cond1, precomputes[offset1])); } else { p = p.add(constTimeNegate(cond2, precomputes[offset2])); } } return { p: p, f: f }; }, wNAFCached: function wNAFCached(P, precomputesMap, n, transform) { var W = P._WINDOW_SIZE || 1; var comp = precomputesMap.get(P); if (!comp) { comp = this.precomputeWindow(P, W); if (W !== 1) { precomputesMap.set(P, transform(comp)); } } return this.wNAF(W, comp, n); } }; } function validateBasic(curve) { validateField(curve.Fp); validateObject(curve, { n: "bigint", h: "bigint", Gx: "field", Gy: "field" }, { nBitLength: "isSafeInteger", nByteLength: "isSafeInteger" }); return Object.freeze(_object_spread({}, nLength(curve.n, curve.nBitLength), curve, { p: curve.Fp.ORDER })); } // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/abstract/weierstrass.js function validatePointOpts(curve) { var opts = validateBasic(curve); validateObject(opts, { a: "field", b: "field" }, { allowedPrivateKeyLengths: "array", wrapPrivateKey: "boolean", isTorsionFree: "function", clearCofactor: "function", allowInfinityPoint: "boolean", fromBytes: "function", toBytes: "function" }); var endo = opts.endo, Fp = opts.Fp, a = opts.a; if (endo) { if (!Fp.eql(a, Fp.ZERO)) { throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0"); } if (typeof endo !== "object" || _type_of(endo.beta) !== "bigint" || typeof endo.splitScalar !== "function") { throw new Error("Expected endomorphism with beta: bigint and splitScalar: function"); } } return Object.freeze(_object_spread({}, opts)); } var b2n = utils_exports.bytesToNumberBE, h2b = utils_exports.hexToBytes; var DER = { // asn.1 DER encoding utils Err: /*#__PURE__*/ function(Error1) { _inherits(DERErr, Error1); var _super = _create_super(DERErr); function DERErr() { var m = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : ""; _class_call_check(this, DERErr); return _super.call(this, m); } return DERErr; }(_wrap_native_super(Error)), _parseInt: function _parseInt(data) { var E = DER.Err; if (data.length < 2 || data[0] !== 2) throw new E("Invalid signature integer tag"); var len = data[1]; var res = data.subarray(2, len + 2); if (!len || res.length !== len) throw new E("Invalid signature integer: wrong length"); if (res[0] & 128) throw new E("Invalid signature integer: negative"); if (res[0] === 0 && !(res[1] & 128)) throw new E("Invalid signature integer: unnecessary leading zero"); return { d: b2n(res), l: data.subarray(len + 2) }; }, toSig: function toSig(hex) { var E = DER.Err; var data = typeof hex === "string" ? h2b(hex) : hex; if (!_instanceof(data, Uint8Array)) throw new Err