index.js 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837
  1. module.exports =
  2. /******/ (function(modules) { // webpackBootstrap
  3. /******/ // The module cache
  4. /******/ var installedModules = {};
  5. /******/
  6. /******/ // The require function
  7. /******/ function __webpack_require__(moduleId) {
  8. /******/
  9. /******/ // Check if module is in cache
  10. /******/ if(installedModules[moduleId]) {
  11. /******/ return installedModules[moduleId].exports;
  12. /******/ }
  13. /******/ // Create a new module (and put it into the cache)
  14. /******/ var module = installedModules[moduleId] = {
  15. /******/ i: moduleId,
  16. /******/ l: false,
  17. /******/ exports: {}
  18. /******/ };
  19. /******/
  20. /******/ // Execute the module function
  21. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  22. /******/
  23. /******/ // Flag the module as loaded
  24. /******/ module.l = true;
  25. /******/
  26. /******/ // Return the exports of the module
  27. /******/ return module.exports;
  28. /******/ }
  29. /******/
  30. /******/
  31. /******/ // expose the modules object (__webpack_modules__)
  32. /******/ __webpack_require__.m = modules;
  33. /******/
  34. /******/ // expose the module cache
  35. /******/ __webpack_require__.c = installedModules;
  36. /******/
  37. /******/ // define getter function for harmony exports
  38. /******/ __webpack_require__.d = function(exports, name, getter) {
  39. /******/ if(!__webpack_require__.o(exports, name)) {
  40. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  41. /******/ }
  42. /******/ };
  43. /******/
  44. /******/ // define __esModule on exports
  45. /******/ __webpack_require__.r = function(exports) {
  46. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  47. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  48. /******/ }
  49. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  50. /******/ };
  51. /******/
  52. /******/ // create a fake namespace object
  53. /******/ // mode & 1: value is a module id, require it
  54. /******/ // mode & 2: merge all properties of value into the ns
  55. /******/ // mode & 4: return value when already ns object
  56. /******/ // mode & 8|1: behave like require
  57. /******/ __webpack_require__.t = function(value, mode) {
  58. /******/ if(mode & 1) value = __webpack_require__(value);
  59. /******/ if(mode & 8) return value;
  60. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  61. /******/ var ns = Object.create(null);
  62. /******/ __webpack_require__.r(ns);
  63. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  64. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  65. /******/ return ns;
  66. /******/ };
  67. /******/
  68. /******/ // getDefaultExport function for compatibility with non-harmony modules
  69. /******/ __webpack_require__.n = function(module) {
  70. /******/ var getter = module && module.__esModule ?
  71. /******/ function getDefault() { return module['default']; } :
  72. /******/ function getModuleExports() { return module; };
  73. /******/ __webpack_require__.d(getter, 'a', getter);
  74. /******/ return getter;
  75. /******/ };
  76. /******/
  77. /******/ // Object.prototype.hasOwnProperty.call
  78. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  79. /******/
  80. /******/ // __webpack_public_path__
  81. /******/ __webpack_require__.p = "";
  82. /******/
  83. /******/
  84. /******/ // Load entry module and return exports
  85. /******/ return __webpack_require__(__webpack_require__.s = 2);
  86. /******/ })
  87. /************************************************************************/
  88. /******/ ([
  89. /* 0 */
  90. /***/ (function(module, exports) {
  91. module.exports = require("jsbn");
  92. /***/ }),
  93. /* 1 */
  94. /***/ (function(module, exports, __webpack_require__) {
  95. "use strict";
  96. // 消息扩展
  97. var W = new Uint32Array(68);
  98. var M = new Uint32Array(64); // W'
  99. /**
  100. * 循环左移
  101. */
  102. function rotl(x, n) {
  103. var s = n & 31;
  104. return x << s | x >>> 32 - s;
  105. }
  106. /**
  107. * 二进制异或运算
  108. */
  109. function xor(x, y) {
  110. var result = [];
  111. for (var i = x.length - 1; i >= 0; i--) {
  112. result[i] = (x[i] ^ y[i]) & 0xff;
  113. }return result;
  114. }
  115. /**
  116. * 压缩函数中的置换函数 P0(X) = X xor (X <<< 9) xor (X <<< 17)
  117. */
  118. function P0(X) {
  119. return X ^ rotl(X, 9) ^ rotl(X, 17);
  120. }
  121. /**
  122. * 消息扩展中的置换函数 P1(X) = X xor (X <<< 15) xor (X <<< 23)
  123. */
  124. function P1(X) {
  125. return X ^ rotl(X, 15) ^ rotl(X, 23);
  126. }
  127. /**
  128. * sm3 本体
  129. */
  130. function sm3(array) {
  131. var len = array.length * 8;
  132. // k 是满足 len + 1 + k = 448mod512 的最小的非负整数
  133. var k = len % 512;
  134. // 如果 448 <= (512 % len) < 512,需要多补充 (len % 448) 比特'0'以满足总比特长度为512的倍数
  135. k = k >= 448 ? 512 - k % 448 - 1 : 448 - k - 1;
  136. // 填充
  137. var kArr = new Array((k - 7) / 8);
  138. var lenArr = new Array(8);
  139. for (var i = 0, _len = kArr.length; i < _len; i++) {
  140. kArr[i] = 0;
  141. }for (var _i = 0, _len2 = lenArr.length; _i < _len2; _i++) {
  142. lenArr[_i] = 0;
  143. }len = len.toString(2);
  144. for (var _i2 = 7; _i2 >= 0; _i2--) {
  145. if (len.length > 8) {
  146. var start = len.length - 8;
  147. lenArr[_i2] = parseInt(len.substr(start), 2);
  148. len = len.substr(0, start);
  149. } else if (len.length > 0) {
  150. lenArr[_i2] = parseInt(len, 2);
  151. len = '';
  152. }
  153. }
  154. var m = new Uint8Array([].concat(array, [0x80], kArr, lenArr));
  155. var dataView = new DataView(m.buffer, 0);
  156. // 迭代压缩
  157. var n = m.length / 64;
  158. var V = new Uint32Array([0x7380166f, 0x4914b2b9, 0x172442d7, 0xda8a0600, 0xa96f30bc, 0x163138aa, 0xe38dee4d, 0xb0fb0e4e]);
  159. for (var _i3 = 0; _i3 < n; _i3++) {
  160. W.fill(0);
  161. M.fill(0);
  162. // 将消息分组B划分为 16 个字 W0, W1,……,W15
  163. var _start = 16 * _i3;
  164. for (var j = 0; j < 16; j++) {
  165. W[j] = dataView.getUint32((_start + j) * 4, false);
  166. }
  167. // W16 ~ W67:W[j] <- P1(W[j−16] xor W[j−9] xor (W[j−3] <<< 15)) xor (W[j−13] <<< 7) xor W[j−6]
  168. for (var _j = 16; _j < 68; _j++) {
  169. W[_j] = P1(W[_j - 16] ^ W[_j - 9] ^ rotl(W[_j - 3], 15)) ^ rotl(W[_j - 13], 7) ^ W[_j - 6];
  170. }
  171. // W′0 ~ W′63:W′[j] = W[j] xor W[j+4]
  172. for (var _j2 = 0; _j2 < 64; _j2++) {
  173. M[_j2] = W[_j2] ^ W[_j2 + 4];
  174. }
  175. // 压缩
  176. var T1 = 0x79cc4519;
  177. var T2 = 0x7a879d8a;
  178. // 字寄存器
  179. var A = V[0];
  180. var B = V[1];
  181. var C = V[2];
  182. var D = V[3];
  183. var E = V[4];
  184. var F = V[5];
  185. var G = V[6];
  186. var H = V[7];
  187. // 中间变量
  188. var SS1 = void 0;
  189. var SS2 = void 0;
  190. var TT1 = void 0;
  191. var TT2 = void 0;
  192. var T = void 0;
  193. for (var _j3 = 0; _j3 < 64; _j3++) {
  194. T = _j3 >= 0 && _j3 <= 15 ? T1 : T2;
  195. SS1 = rotl(rotl(A, 12) + E + rotl(T, _j3), 7);
  196. SS2 = SS1 ^ rotl(A, 12);
  197. TT1 = (_j3 >= 0 && _j3 <= 15 ? A ^ B ^ C : A & B | A & C | B & C) + D + SS2 + M[_j3];
  198. TT2 = (_j3 >= 0 && _j3 <= 15 ? E ^ F ^ G : E & F | ~E & G) + H + SS1 + W[_j3];
  199. D = C;
  200. C = rotl(B, 9);
  201. B = A;
  202. A = TT1;
  203. H = G;
  204. G = rotl(F, 19);
  205. F = E;
  206. E = P0(TT2);
  207. }
  208. V[0] ^= A;
  209. V[1] ^= B;
  210. V[2] ^= C;
  211. V[3] ^= D;
  212. V[4] ^= E;
  213. V[5] ^= F;
  214. V[6] ^= G;
  215. V[7] ^= H;
  216. }
  217. // 转回 uint8
  218. var result = [];
  219. for (var _i4 = 0, _len3 = V.length; _i4 < _len3; _i4++) {
  220. var word = V[_i4];
  221. result.push((word & 0xff000000) >>> 24, (word & 0xff0000) >>> 16, (word & 0xff00) >>> 8, word & 0xff);
  222. }
  223. return result;
  224. }
  225. /**
  226. * hmac 实现
  227. */
  228. var blockLen = 64;
  229. var iPad = new Uint8Array(blockLen);
  230. var oPad = new Uint8Array(blockLen);
  231. for (var i = 0; i < blockLen; i++) {
  232. iPad[i] = 0x36;
  233. oPad[i] = 0x5c;
  234. }
  235. function hmac(input, key) {
  236. // 密钥填充
  237. if (key.length > blockLen) key = sm3(key);
  238. while (key.length < blockLen) {
  239. key.push(0);
  240. }var iPadKey = xor(key, iPad);
  241. var oPadKey = xor(key, oPad);
  242. var hash = sm3([].concat(iPadKey, input));
  243. return sm3([].concat(oPadKey, hash));
  244. }
  245. module.exports = {
  246. sm3: sm3,
  247. hmac: hmac
  248. };
  249. /***/ }),
  250. /* 2 */
  251. /***/ (function(module, exports, __webpack_require__) {
  252. "use strict";
  253. module.exports = {
  254. sm2: __webpack_require__(3),
  255. sm3: __webpack_require__(7),
  256. sm4: __webpack_require__(8)
  257. };
  258. /***/ }),
  259. /* 3 */
  260. /***/ (function(module, exports, __webpack_require__) {
  261. "use strict";
  262. /* eslint-disable no-use-before-define */
  263. var _require = __webpack_require__(0),
  264. BigInteger = _require.BigInteger;
  265. var _require2 = __webpack_require__(4),
  266. encodeDer = _require2.encodeDer,
  267. decodeDer = _require2.decodeDer;
  268. var _ = __webpack_require__(5);
  269. var sm3 = __webpack_require__(1).sm3;
  270. var _$generateEcparam = _.generateEcparam(),
  271. G = _$generateEcparam.G,
  272. curve = _$generateEcparam.curve,
  273. n = _$generateEcparam.n;
  274. var C1C2C3 = 0;
  275. /**
  276. * 加密
  277. */
  278. function doEncrypt(msg, publicKey) {
  279. var cipherMode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  280. msg = typeof msg === 'string' ? _.hexToArray(_.utf8ToHex(msg)) : Array.prototype.slice.call(msg);
  281. publicKey = _.getGlobalCurve().decodePointHex(publicKey); // 先将公钥转成点
  282. var keypair = _.generateKeyPairHex();
  283. var k = new BigInteger(keypair.privateKey, 16); // 随机数 k
  284. // c1 = k * G
  285. var c1 = keypair.publicKey;
  286. if (c1.length > 128) c1 = c1.substr(c1.length - 128);
  287. // (x2, y2) = k * publicKey
  288. var p = publicKey.multiply(k);
  289. var x2 = _.hexToArray(_.leftPad(p.getX().toBigInteger().toRadix(16), 64));
  290. var y2 = _.hexToArray(_.leftPad(p.getY().toBigInteger().toRadix(16), 64));
  291. // c3 = hash(x2 || msg || y2)
  292. var c3 = _.arrayToHex(sm3([].concat(x2, msg, y2)));
  293. var ct = 1;
  294. var offset = 0;
  295. var t = []; // 256 位
  296. var z = [].concat(x2, y2);
  297. var nextT = function nextT() {
  298. // (1) Hai = hash(z || ct)
  299. // (2) ct++
  300. t = sm3([].concat(z, [ct >> 24 & 0x00ff, ct >> 16 & 0x00ff, ct >> 8 & 0x00ff, ct & 0x00ff]));
  301. ct++;
  302. offset = 0;
  303. };
  304. nextT(); // 先生成 Ha1
  305. for (var i = 0, len = msg.length; i < len; i++) {
  306. // t = Ha1 || Ha2 || Ha3 || Ha4
  307. if (offset === t.length) nextT();
  308. // c2 = msg ^ t
  309. msg[i] ^= t[offset++] & 0xff;
  310. }
  311. var c2 = _.arrayToHex(msg);
  312. return cipherMode === C1C2C3 ? c1 + c2 + c3 : c1 + c3 + c2;
  313. }
  314. /**
  315. * 解密
  316. */
  317. function doDecrypt(encryptData, privateKey) {
  318. var cipherMode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  319. var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {},
  320. _ref$output = _ref.output,
  321. output = _ref$output === undefined ? 'string' : _ref$output;
  322. privateKey = new BigInteger(privateKey, 16);
  323. var c3 = encryptData.substr(128, 64);
  324. var c2 = encryptData.substr(128 + 64);
  325. if (cipherMode === C1C2C3) {
  326. c3 = encryptData.substr(encryptData.length - 64);
  327. c2 = encryptData.substr(128, encryptData.length - 128 - 64);
  328. }
  329. var msg = _.hexToArray(c2);
  330. var c1 = _.getGlobalCurve().decodePointHex('04' + encryptData.substr(0, 128));
  331. var p = c1.multiply(privateKey);
  332. var x2 = _.hexToArray(_.leftPad(p.getX().toBigInteger().toRadix(16), 64));
  333. var y2 = _.hexToArray(_.leftPad(p.getY().toBigInteger().toRadix(16), 64));
  334. var ct = 1;
  335. var offset = 0;
  336. var t = []; // 256 位
  337. var z = [].concat(x2, y2);
  338. var nextT = function nextT() {
  339. // (1) Hai = hash(z || ct)
  340. // (2) ct++
  341. t = sm3([].concat(z, [ct >> 24 & 0x00ff, ct >> 16 & 0x00ff, ct >> 8 & 0x00ff, ct & 0x00ff]));
  342. ct++;
  343. offset = 0;
  344. };
  345. nextT(); // 先生成 Ha1
  346. for (var i = 0, len = msg.length; i < len; i++) {
  347. // t = Ha1 || Ha2 || Ha3 || Ha4
  348. if (offset === t.length) nextT();
  349. // c2 = msg ^ t
  350. msg[i] ^= t[offset++] & 0xff;
  351. }
  352. // c3 = hash(x2 || msg || y2)
  353. var checkC3 = _.arrayToHex(sm3([].concat(x2, msg, y2)));
  354. if (checkC3 === c3.toLowerCase()) {
  355. return output === 'array' ? msg : _.arrayToUtf8(msg);
  356. } else {
  357. return output === 'array' ? [] : '';
  358. }
  359. }
  360. /**
  361. * 签名
  362. */
  363. function doSignature(msg, privateKey) {
  364. var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
  365. pointPool = _ref2.pointPool,
  366. der = _ref2.der,
  367. hash = _ref2.hash,
  368. publicKey = _ref2.publicKey,
  369. userId = _ref2.userId;
  370. var hashHex = typeof msg === 'string' ? _.utf8ToHex(msg) : _.arrayToHex(msg);
  371. if (hash) {
  372. // sm3杂凑
  373. publicKey = publicKey || getPublicKeyFromPrivateKey(privateKey);
  374. hashHex = getHash(hashHex, publicKey, userId);
  375. }
  376. var dA = new BigInteger(privateKey, 16);
  377. var e = new BigInteger(hashHex, 16);
  378. // k
  379. var k = null;
  380. var r = null;
  381. var s = null;
  382. do {
  383. do {
  384. var point = void 0;
  385. if (pointPool && pointPool.length) {
  386. point = pointPool.pop();
  387. } else {
  388. point = getPoint();
  389. }
  390. k = point.k;
  391. // r = (e + x1) mod n
  392. r = e.add(point.x1).mod(n);
  393. } while (r.equals(BigInteger.ZERO) || r.add(k).equals(n));
  394. // s = ((1 + dA)^-1 * (k - r * dA)) mod n
  395. s = dA.add(BigInteger.ONE).modInverse(n).multiply(k.subtract(r.multiply(dA))).mod(n);
  396. } while (s.equals(BigInteger.ZERO));
  397. if (der) return encodeDer(r, s); // asn.1 der 编码
  398. return _.leftPad(r.toString(16), 64) + _.leftPad(s.toString(16), 64);
  399. }
  400. /**
  401. * 验签
  402. */
  403. function doVerifySignature(msg, signHex, publicKey) {
  404. var _ref3 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {},
  405. der = _ref3.der,
  406. hash = _ref3.hash,
  407. userId = _ref3.userId;
  408. var hashHex = typeof msg === 'string' ? _.utf8ToHex(msg) : _.arrayToHex(msg);
  409. if (hash) {
  410. // sm3杂凑
  411. hashHex = getHash(hashHex, publicKey, userId);
  412. }
  413. var r = void 0;var s = void 0;
  414. if (der) {
  415. var decodeDerObj = decodeDer(signHex); // asn.1 der 解码
  416. r = decodeDerObj.r;
  417. s = decodeDerObj.s;
  418. } else {
  419. r = new BigInteger(signHex.substring(0, 64), 16);
  420. s = new BigInteger(signHex.substring(64), 16);
  421. }
  422. var PA = curve.decodePointHex(publicKey);
  423. var e = new BigInteger(hashHex, 16);
  424. // t = (r + s) mod n
  425. var t = r.add(s).mod(n);
  426. if (t.equals(BigInteger.ZERO)) return false;
  427. // x1y1 = s * G + t * PA
  428. var x1y1 = G.multiply(s).add(PA.multiply(t));
  429. // R = (e + x1) mod n
  430. var R = e.add(x1y1.getX().toBigInteger()).mod(n);
  431. return r.equals(R);
  432. }
  433. /**
  434. * sm3杂凑算法
  435. */
  436. function getHash(hashHex, publicKey) {
  437. var userId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '1234567812345678';
  438. // z = hash(entl || userId || a || b || gx || gy || px || py)
  439. userId = _.utf8ToHex(userId);
  440. var a = _.leftPad(G.curve.a.toBigInteger().toRadix(16), 64);
  441. var b = _.leftPad(G.curve.b.toBigInteger().toRadix(16), 64);
  442. var gx = _.leftPad(G.getX().toBigInteger().toRadix(16), 64);
  443. var gy = _.leftPad(G.getY().toBigInteger().toRadix(16), 64);
  444. var px = void 0;
  445. var py = void 0;
  446. if (publicKey.length === 128) {
  447. px = publicKey.substr(0, 64);
  448. py = publicKey.substr(64, 64);
  449. } else {
  450. var point = G.curve.decodePointHex(publicKey);
  451. px = _.leftPad(point.getX().toBigInteger().toRadix(16), 64);
  452. py = _.leftPad(point.getY().toBigInteger().toRadix(16), 64);
  453. }
  454. var data = _.hexToArray(userId + a + b + gx + gy + px + py);
  455. var entl = userId.length * 4;
  456. data.unshift(entl & 0x00ff);
  457. data.unshift(entl >> 8 & 0x00ff);
  458. var z = sm3(data);
  459. // e = hash(z || msg)
  460. return _.arrayToHex(sm3(z.concat(_.hexToArray(hashHex))));
  461. }
  462. /**
  463. * 计算公钥
  464. */
  465. function getPublicKeyFromPrivateKey(privateKey) {
  466. var PA = G.multiply(new BigInteger(privateKey, 16));
  467. var x = _.leftPad(PA.getX().toBigInteger().toString(16), 64);
  468. var y = _.leftPad(PA.getY().toBigInteger().toString(16), 64);
  469. return '04' + x + y;
  470. }
  471. /**
  472. * 获取椭圆曲线点
  473. */
  474. function getPoint() {
  475. var keypair = _.generateKeyPairHex();
  476. var PA = curve.decodePointHex(keypair.publicKey);
  477. keypair.k = new BigInteger(keypair.privateKey, 16);
  478. keypair.x1 = PA.getX().toBigInteger();
  479. return keypair;
  480. }
  481. module.exports = {
  482. generateKeyPairHex: _.generateKeyPairHex,
  483. compressPublicKeyHex: _.compressPublicKeyHex,
  484. comparePublicKeyHex: _.comparePublicKeyHex,
  485. doEncrypt: doEncrypt,
  486. doDecrypt: doDecrypt,
  487. doSignature: doSignature,
  488. doVerifySignature: doVerifySignature,
  489. getPublicKeyFromPrivateKey: getPublicKeyFromPrivateKey,
  490. getPoint: getPoint,
  491. verifyPublicKey: _.verifyPublicKey
  492. };
  493. /***/ }),
  494. /* 4 */
  495. /***/ (function(module, exports, __webpack_require__) {
  496. "use strict";
  497. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  498. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  499. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  500. /* eslint-disable class-methods-use-this */
  501. var _require = __webpack_require__(0),
  502. BigInteger = _require.BigInteger;
  503. function bigintToValue(bigint) {
  504. var h = bigint.toString(16);
  505. if (h[0] !== '-') {
  506. // 正数
  507. if (h.length % 2 === 1) h = '0' + h; // 补齐到整字节
  508. else if (!h.match(/^[0-7]/)) h = '00' + h; // 非0开头,则补一个全0字节
  509. } else {
  510. // 负数
  511. h = h.substr(1);
  512. var len = h.length;
  513. if (len % 2 === 1) len += 1; // 补齐到整字节
  514. else if (!h.match(/^[0-7]/)) len += 2; // 非0开头,则补一个全0字节
  515. var mask = '';
  516. for (var i = 0; i < len; i++) {
  517. mask += 'f';
  518. }mask = new BigInteger(mask, 16);
  519. // 对绝对值取反,加1
  520. h = mask.xor(bigint).add(BigInteger.ONE);
  521. h = h.toString(16).replace(/^-/, '');
  522. }
  523. return h;
  524. }
  525. var ASN1Object = function () {
  526. function ASN1Object() {
  527. _classCallCheck(this, ASN1Object);
  528. this.tlv = null;
  529. this.t = '00';
  530. this.l = '00';
  531. this.v = '';
  532. }
  533. /**
  534. * 获取 der 编码比特流16进制串
  535. */
  536. ASN1Object.prototype.getEncodedHex = function getEncodedHex() {
  537. if (!this.tlv) {
  538. this.v = this.getValue();
  539. this.l = this.getLength();
  540. this.tlv = this.t + this.l + this.v;
  541. }
  542. return this.tlv;
  543. };
  544. ASN1Object.prototype.getLength = function getLength() {
  545. var n = this.v.length / 2; // 字节数
  546. var nHex = n.toString(16);
  547. if (nHex.length % 2 === 1) nHex = '0' + nHex; // 补齐到整字节
  548. if (n < 128) {
  549. // 短格式,以 0 开头
  550. return nHex;
  551. } else {
  552. // 长格式,以 1 开头
  553. var head = 128 + nHex.length / 2; // 1(1位) + 真正的长度占用字节数(7位) + 真正的长度
  554. return head.toString(16) + nHex;
  555. }
  556. };
  557. ASN1Object.prototype.getValue = function getValue() {
  558. return '';
  559. };
  560. return ASN1Object;
  561. }();
  562. var DERInteger = function (_ASN1Object) {
  563. _inherits(DERInteger, _ASN1Object);
  564. function DERInteger(bigint) {
  565. _classCallCheck(this, DERInteger);
  566. var _this = _possibleConstructorReturn(this, _ASN1Object.call(this));
  567. _this.t = '02'; // 整型标签说明
  568. if (bigint) _this.v = bigintToValue(bigint);
  569. return _this;
  570. }
  571. DERInteger.prototype.getValue = function getValue() {
  572. return this.v;
  573. };
  574. return DERInteger;
  575. }(ASN1Object);
  576. var DERSequence = function (_ASN1Object2) {
  577. _inherits(DERSequence, _ASN1Object2);
  578. function DERSequence(asn1Array) {
  579. _classCallCheck(this, DERSequence);
  580. var _this2 = _possibleConstructorReturn(this, _ASN1Object2.call(this));
  581. _this2.t = '30'; // 序列标签说明
  582. _this2.asn1Array = asn1Array;
  583. return _this2;
  584. }
  585. DERSequence.prototype.getValue = function getValue() {
  586. this.v = this.asn1Array.map(function (asn1Object) {
  587. return asn1Object.getEncodedHex();
  588. }).join('');
  589. return this.v;
  590. };
  591. return DERSequence;
  592. }(ASN1Object);
  593. /**
  594. * 获取 l 占用字节数
  595. */
  596. function getLenOfL(str, start) {
  597. if (+str[start + 2] < 8) return 1; // l 以0开头,则表示短格式,只占一个字节
  598. return +str.substr(start + 2, 2) & 0x7f + 1; // 长格式,取第一个字节后7位作为长度真正占用字节数,再加上本身
  599. }
  600. /**
  601. * 获取 l
  602. */
  603. function getL(str, start) {
  604. // 获取 l
  605. var len = getLenOfL(str, start);
  606. var l = str.substr(start + 2, len * 2);
  607. if (!l) return -1;
  608. var bigint = +l[0] < 8 ? new BigInteger(l, 16) : new BigInteger(l.substr(2), 16);
  609. return bigint.intValue();
  610. }
  611. /**
  612. * 获取 v 的位置
  613. */
  614. function getStartOfV(str, start) {
  615. var len = getLenOfL(str, start);
  616. return start + (len + 1) * 2;
  617. }
  618. module.exports = {
  619. /**
  620. * ASN.1 der 编码,针对 sm2 签名
  621. */
  622. encodeDer: function encodeDer(r, s) {
  623. var derR = new DERInteger(r);
  624. var derS = new DERInteger(s);
  625. var derSeq = new DERSequence([derR, derS]);
  626. return derSeq.getEncodedHex();
  627. },
  628. /**
  629. * 解析 ASN.1 der,针对 sm2 验签
  630. */
  631. decodeDer: function decodeDer(input) {
  632. // 结构:
  633. // input = | tSeq | lSeq | vSeq |
  634. // vSeq = | tR | lR | vR | tS | lS | vS |
  635. var start = getStartOfV(input, 0);
  636. var vIndexR = getStartOfV(input, start);
  637. var lR = getL(input, start);
  638. var vR = input.substr(vIndexR, lR * 2);
  639. var nextStart = vIndexR + vR.length;
  640. var vIndexS = getStartOfV(input, nextStart);
  641. var lS = getL(input, nextStart);
  642. var vS = input.substr(vIndexS, lS * 2);
  643. var r = new BigInteger(vR, 16);
  644. var s = new BigInteger(vS, 16);
  645. return { r: r, s: s };
  646. }
  647. };
  648. /***/ }),
  649. /* 5 */
  650. /***/ (function(module, exports, __webpack_require__) {
  651. "use strict";
  652. /* eslint-disable no-bitwise, no-mixed-operators, no-use-before-define, max-len */
  653. var _require = __webpack_require__(0),
  654. BigInteger = _require.BigInteger,
  655. SecureRandom = _require.SecureRandom;
  656. var _require2 = __webpack_require__(6),
  657. ECCurveFp = _require2.ECCurveFp;
  658. var rng = new SecureRandom();
  659. var _generateEcparam = generateEcparam(),
  660. curve = _generateEcparam.curve,
  661. G = _generateEcparam.G,
  662. n = _generateEcparam.n;
  663. /**
  664. * 获取公共椭圆曲线
  665. */
  666. function getGlobalCurve() {
  667. return curve;
  668. }
  669. /**
  670. * 生成ecparam
  671. */
  672. function generateEcparam() {
  673. // 椭圆曲线
  674. var p = new BigInteger('FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF', 16);
  675. var a = new BigInteger('FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC', 16);
  676. var b = new BigInteger('28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93', 16);
  677. var curve = new ECCurveFp(p, a, b);
  678. // 基点
  679. var gxHex = '32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7';
  680. var gyHex = 'BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0';
  681. var G = curve.decodePointHex('04' + gxHex + gyHex);
  682. var n = new BigInteger('FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123', 16);
  683. return { curve: curve, G: G, n: n };
  684. }
  685. /**
  686. * 生成密钥对:publicKey = privateKey * G
  687. */
  688. function generateKeyPairHex(a, b, c) {
  689. var random = a ? new BigInteger(a, b, c) : new BigInteger(n.bitLength(), rng);
  690. var d = random.mod(n.subtract(BigInteger.ONE)).add(BigInteger.ONE); // 随机数
  691. var privateKey = leftPad(d.toString(16), 64);
  692. var P = G.multiply(d); // P = dG,p 为公钥,d 为私钥
  693. var Px = leftPad(P.getX().toBigInteger().toString(16), 64);
  694. var Py = leftPad(P.getY().toBigInteger().toString(16), 64);
  695. var publicKey = '04' + Px + Py;
  696. return { privateKey: privateKey, publicKey: publicKey };
  697. }
  698. /**
  699. * 生成压缩公钥
  700. */
  701. function compressPublicKeyHex(s) {
  702. if (s.length !== 130) throw new Error('Invalid public key to compress');
  703. var len = (s.length - 2) / 2;
  704. var xHex = s.substr(2, len);
  705. var y = new BigInteger(s.substr(len + 2, len), 16);
  706. var prefix = '03';
  707. if (y.mod(new BigInteger('2')).equals(BigInteger.ZERO)) prefix = '02';
  708. return prefix + xHex;
  709. }
  710. /**
  711. * utf8串转16进制串
  712. */
  713. function utf8ToHex(input) {
  714. input = unescape(encodeURIComponent(input));
  715. var length = input.length;
  716. // 转换到字数组
  717. var words = [];
  718. for (var i = 0; i < length; i++) {
  719. words[i >>> 2] |= (input.charCodeAt(i) & 0xff) << 24 - i % 4 * 8;
  720. }
  721. // 转换到16进制
  722. var hexChars = [];
  723. for (var _i = 0; _i < length; _i++) {
  724. var bite = words[_i >>> 2] >>> 24 - _i % 4 * 8 & 0xff;
  725. hexChars.push((bite >>> 4).toString(16));
  726. hexChars.push((bite & 0x0f).toString(16));
  727. }
  728. return hexChars.join('');
  729. }
  730. /**
  731. * 补全16进制字符串
  732. */
  733. function leftPad(input, num) {
  734. if (input.length >= num) return input;
  735. return new Array(num - input.length + 1).join('0') + input;
  736. }
  737. /**
  738. * 转成16进制串
  739. */
  740. function arrayToHex(arr) {
  741. return arr.map(function (item) {
  742. item = item.toString(16);
  743. return item.length === 1 ? '0' + item : item;
  744. }).join('');
  745. }
  746. /**
  747. * 转成utf8串
  748. */
  749. function arrayToUtf8(arr) {
  750. var words = [];
  751. var j = 0;
  752. for (var i = 0; i < arr.length * 2; i += 2) {
  753. words[i >>> 3] |= parseInt(arr[j], 10) << 24 - i % 8 * 4;
  754. j++;
  755. }
  756. try {
  757. var latin1Chars = [];
  758. for (var _i2 = 0; _i2 < arr.length; _i2++) {
  759. var bite = words[_i2 >>> 2] >>> 24 - _i2 % 4 * 8 & 0xff;
  760. latin1Chars.push(String.fromCharCode(bite));
  761. }
  762. return decodeURIComponent(escape(latin1Chars.join('')));
  763. } catch (e) {
  764. throw new Error('Malformed UTF-8 data');
  765. }
  766. }
  767. /**
  768. * 转成字节数组
  769. */
  770. function hexToArray(hexStr) {
  771. var words = [];
  772. var hexStrLength = hexStr.length;
  773. if (hexStrLength % 2 !== 0) {
  774. hexStr = leftPad(hexStr, hexStrLength + 1);
  775. }
  776. hexStrLength = hexStr.length;
  777. for (var i = 0; i < hexStrLength; i += 2) {
  778. words.push(parseInt(hexStr.substr(i, 2), 16));
  779. }
  780. return words;
  781. }
  782. /**
  783. * 验证公钥是否为椭圆曲线上的点
  784. */
  785. function verifyPublicKey(publicKey) {
  786. var point = curve.decodePointHex(publicKey);
  787. if (!point) return false;
  788. var x = point.getX();
  789. var y = point.getY();
  790. // 验证 y^2 是否等于 x^3 + ax + b
  791. return y.square().equals(x.multiply(x.square()).add(x.multiply(curve.a)).add(curve.b));
  792. }
  793. /**
  794. * 验证公钥是否等价,等价返回true
  795. */
  796. function comparePublicKeyHex(publicKey1, publicKey2) {
  797. var point1 = curve.decodePointHex(publicKey1);
  798. if (!point1) return false;
  799. var point2 = curve.decodePointHex(publicKey2);
  800. if (!point2) return false;
  801. return point1.equals(point2);
  802. }
  803. module.exports = {
  804. getGlobalCurve: getGlobalCurve,
  805. generateEcparam: generateEcparam,
  806. generateKeyPairHex: generateKeyPairHex,
  807. compressPublicKeyHex: compressPublicKeyHex,
  808. utf8ToHex: utf8ToHex,
  809. leftPad: leftPad,
  810. arrayToHex: arrayToHex,
  811. arrayToUtf8: arrayToUtf8,
  812. hexToArray: hexToArray,
  813. verifyPublicKey: verifyPublicKey,
  814. comparePublicKeyHex: comparePublicKeyHex
  815. };
  816. /***/ }),
  817. /* 6 */
  818. /***/ (function(module, exports, __webpack_require__) {
  819. "use strict";
  820. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  821. /* eslint-disable no-case-declarations, max-len */
  822. var _require = __webpack_require__(0),
  823. BigInteger = _require.BigInteger;
  824. /**
  825. * thanks for Tom Wu : http://www-cs-students.stanford.edu/~tjw/jsbn/
  826. *
  827. * Basic Javascript Elliptic Curve implementation
  828. * Ported loosely from BouncyCastle's Java EC code
  829. * Only Fp curves implemented for now
  830. */
  831. var TWO = new BigInteger('2');
  832. var THREE = new BigInteger('3');
  833. /**
  834. * 椭圆曲线域元素
  835. */
  836. var ECFieldElementFp = function () {
  837. function ECFieldElementFp(q, x) {
  838. _classCallCheck(this, ECFieldElementFp);
  839. this.x = x;
  840. this.q = q;
  841. // TODO if (x.compareTo(q) >= 0) error
  842. }
  843. /**
  844. * 判断相等
  845. */
  846. ECFieldElementFp.prototype.equals = function equals(other) {
  847. if (other === this) return true;
  848. return this.q.equals(other.q) && this.x.equals(other.x);
  849. };
  850. /**
  851. * 返回具体数值
  852. */
  853. ECFieldElementFp.prototype.toBigInteger = function toBigInteger() {
  854. return this.x;
  855. };
  856. /**
  857. * 取反
  858. */
  859. ECFieldElementFp.prototype.negate = function negate() {
  860. return new ECFieldElementFp(this.q, this.x.negate().mod(this.q));
  861. };
  862. /**
  863. * 相加
  864. */
  865. ECFieldElementFp.prototype.add = function add(b) {
  866. return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q));
  867. };
  868. /**
  869. * 相减
  870. */
  871. ECFieldElementFp.prototype.subtract = function subtract(b) {
  872. return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q));
  873. };
  874. /**
  875. * 相乘
  876. */
  877. ECFieldElementFp.prototype.multiply = function multiply(b) {
  878. return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q));
  879. };
  880. /**
  881. * 相除
  882. */
  883. ECFieldElementFp.prototype.divide = function divide(b) {
  884. return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q));
  885. };
  886. /**
  887. * 平方
  888. */
  889. ECFieldElementFp.prototype.square = function square() {
  890. return new ECFieldElementFp(this.q, this.x.square().mod(this.q));
  891. };
  892. return ECFieldElementFp;
  893. }();
  894. var ECPointFp = function () {
  895. function ECPointFp(curve, x, y, z) {
  896. _classCallCheck(this, ECPointFp);
  897. this.curve = curve;
  898. this.x = x;
  899. this.y = y;
  900. // 标准射影坐标系:zinv == null 或 z * zinv == 1
  901. this.z = z == null ? BigInteger.ONE : z;
  902. this.zinv = null;
  903. // TODO: compression flag
  904. }
  905. ECPointFp.prototype.getX = function getX() {
  906. if (this.zinv === null) this.zinv = this.z.modInverse(this.curve.q);
  907. return this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q));
  908. };
  909. ECPointFp.prototype.getY = function getY() {
  910. if (this.zinv === null) this.zinv = this.z.modInverse(this.curve.q);
  911. return this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q));
  912. };
  913. /**
  914. * 判断相等
  915. */
  916. ECPointFp.prototype.equals = function equals(other) {
  917. if (other === this) return true;
  918. if (this.isInfinity()) return other.isInfinity();
  919. if (other.isInfinity()) return this.isInfinity();
  920. // u = y2 * z1 - y1 * z2
  921. var u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q);
  922. if (!u.equals(BigInteger.ZERO)) return false;
  923. // v = x2 * z1 - x1 * z2
  924. var v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q);
  925. return v.equals(BigInteger.ZERO);
  926. };
  927. /**
  928. * 是否是无穷远点
  929. */
  930. ECPointFp.prototype.isInfinity = function isInfinity() {
  931. if (this.x === null && this.y === null) return true;
  932. return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO);
  933. };
  934. /**
  935. * 取反,x 轴对称点
  936. */
  937. ECPointFp.prototype.negate = function negate() {
  938. return new ECPointFp(this.curve, this.x, this.y.negate(), this.z);
  939. };
  940. /**
  941. * 相加
  942. *
  943. * 标准射影坐标系:
  944. *
  945. * λ1 = x1 * z2
  946. * λ2 = x2 * z1
  947. * λ3 = λ1 − λ2
  948. * λ4 = y1 * z2
  949. * λ5 = y2 * z1
  950. * λ6 = λ4 − λ5
  951. * λ7 = λ1 + λ2
  952. * λ8 = z1 * z2
  953. * λ9 = λ3^2
  954. * λ10 = λ3 * λ9
  955. * λ11 = λ8 * λ6^2 − λ7 * λ9
  956. * x3 = λ3 * λ11
  957. * y3 = λ6 * (λ9 * λ1 − λ11) − λ4 * λ10
  958. * z3 = λ10 * λ8
  959. */
  960. ECPointFp.prototype.add = function add(b) {
  961. if (this.isInfinity()) return b;
  962. if (b.isInfinity()) return this;
  963. var x1 = this.x.toBigInteger();
  964. var y1 = this.y.toBigInteger();
  965. var z1 = this.z;
  966. var x2 = b.x.toBigInteger();
  967. var y2 = b.y.toBigInteger();
  968. var z2 = b.z;
  969. var q = this.curve.q;
  970. var w1 = x1.multiply(z2).mod(q);
  971. var w2 = x2.multiply(z1).mod(q);
  972. var w3 = w1.subtract(w2);
  973. var w4 = y1.multiply(z2).mod(q);
  974. var w5 = y2.multiply(z1).mod(q);
  975. var w6 = w4.subtract(w5);
  976. if (BigInteger.ZERO.equals(w3)) {
  977. if (BigInteger.ZERO.equals(w6)) {
  978. return this.twice(); // this == b,计算自加
  979. }
  980. return this.curve.infinity; // this == -b,则返回无穷远点
  981. }
  982. var w7 = w1.add(w2);
  983. var w8 = z1.multiply(z2).mod(q);
  984. var w9 = w3.square().mod(q);
  985. var w10 = w3.multiply(w9).mod(q);
  986. var w11 = w8.multiply(w6.square()).subtract(w7.multiply(w9)).mod(q);
  987. var x3 = w3.multiply(w11).mod(q);
  988. var y3 = w6.multiply(w9.multiply(w1).subtract(w11)).subtract(w4.multiply(w10)).mod(q);
  989. var z3 = w10.multiply(w8).mod(q);
  990. return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
  991. };
  992. /**
  993. * 自加
  994. *
  995. * 标准射影坐标系:
  996. *
  997. * λ1 = 3 * x1^2 + a * z1^2
  998. * λ2 = 2 * y1 * z1
  999. * λ3 = y1^2
  1000. * λ4 = λ3 * x1 * z1
  1001. * λ5 = λ2^2
  1002. * λ6 = λ1^2 − 8 * λ4
  1003. * x3 = λ2 * λ6
  1004. * y3 = λ1 * (4 * λ4 − λ6) − 2 * λ5 * λ3
  1005. * z3 = λ2 * λ5
  1006. */
  1007. ECPointFp.prototype.twice = function twice() {
  1008. if (this.isInfinity()) return this;
  1009. if (!this.y.toBigInteger().signum()) return this.curve.infinity;
  1010. var x1 = this.x.toBigInteger();
  1011. var y1 = this.y.toBigInteger();
  1012. var z1 = this.z;
  1013. var q = this.curve.q;
  1014. var a = this.curve.a.toBigInteger();
  1015. var w1 = x1.square().multiply(THREE).add(a.multiply(z1.square())).mod(q);
  1016. var w2 = y1.shiftLeft(1).multiply(z1).mod(q);
  1017. var w3 = y1.square().mod(q);
  1018. var w4 = w3.multiply(x1).multiply(z1).mod(q);
  1019. var w5 = w2.square().mod(q);
  1020. var w6 = w1.square().subtract(w4.shiftLeft(3)).mod(q);
  1021. var x3 = w2.multiply(w6).mod(q);
  1022. var y3 = w1.multiply(w4.shiftLeft(2).subtract(w6)).subtract(w5.shiftLeft(1).multiply(w3)).mod(q);
  1023. var z3 = w2.multiply(w5).mod(q);
  1024. return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
  1025. };
  1026. /**
  1027. * 倍点计算
  1028. */
  1029. ECPointFp.prototype.multiply = function multiply(k) {
  1030. if (this.isInfinity()) return this;
  1031. if (!k.signum()) return this.curve.infinity;
  1032. // 使用加减法
  1033. var k3 = k.multiply(THREE);
  1034. var neg = this.negate();
  1035. var Q = this;
  1036. for (var i = k3.bitLength() - 2; i > 0; i--) {
  1037. Q = Q.twice();
  1038. var k3Bit = k3.testBit(i);
  1039. var kBit = k.testBit(i);
  1040. if (k3Bit !== kBit) {
  1041. Q = Q.add(k3Bit ? this : neg);
  1042. }
  1043. }
  1044. return Q;
  1045. };
  1046. return ECPointFp;
  1047. }();
  1048. /**
  1049. * 椭圆曲线 y^2 = x^3 + ax + b
  1050. */
  1051. var ECCurveFp = function () {
  1052. function ECCurveFp(q, a, b) {
  1053. _classCallCheck(this, ECCurveFp);
  1054. this.q = q;
  1055. this.a = this.fromBigInteger(a);
  1056. this.b = this.fromBigInteger(b);
  1057. this.infinity = new ECPointFp(this, null, null); // 无穷远点
  1058. }
  1059. /**
  1060. * 判断两个椭圆曲线是否相等
  1061. */
  1062. ECCurveFp.prototype.equals = function equals(other) {
  1063. if (other === this) return true;
  1064. return this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b);
  1065. };
  1066. /**
  1067. * 生成椭圆曲线域元素
  1068. */
  1069. ECCurveFp.prototype.fromBigInteger = function fromBigInteger(x) {
  1070. return new ECFieldElementFp(this.q, x);
  1071. };
  1072. /**
  1073. * 解析 16 进制串为椭圆曲线点
  1074. */
  1075. ECCurveFp.prototype.decodePointHex = function decodePointHex(s) {
  1076. switch (parseInt(s.substr(0, 2), 16)) {
  1077. // 第一个字节
  1078. case 0:
  1079. return this.infinity;
  1080. case 2:
  1081. case 3:
  1082. // 压缩
  1083. var x = this.fromBigInteger(new BigInteger(s.substr(2), 16));
  1084. // 对 p ≡ 3 (mod4),即存在正整数 u,使得 p = 4u + 3
  1085. // 计算 y = (√ (x^3 + ax + b) % p)^(u + 1) modp
  1086. var y = this.fromBigInteger(x.multiply(x.square()).add(x.multiply(this.a)).add(this.b).toBigInteger().modPow(this.q.divide(new BigInteger('4')).add(BigInteger.ONE), this.q));
  1087. // 算出结果 2 进制最后 1 位不等于第 1 个字节减 2 则取反
  1088. if (!y.toBigInteger().mod(TWO).equals(new BigInteger(s.substr(0, 2), 16).subtract(TWO))) {
  1089. y = y.negate();
  1090. }
  1091. return new ECPointFp(this, x, y);
  1092. case 4:
  1093. case 6:
  1094. case 7:
  1095. var len = (s.length - 2) / 2;
  1096. var xHex = s.substr(2, len);
  1097. var yHex = s.substr(len + 2, len);
  1098. return new ECPointFp(this, this.fromBigInteger(new BigInteger(xHex, 16)), this.fromBigInteger(new BigInteger(yHex, 16)));
  1099. default:
  1100. // 不支持
  1101. return null;
  1102. }
  1103. };
  1104. return ECCurveFp;
  1105. }();
  1106. module.exports = {
  1107. ECPointFp: ECPointFp,
  1108. ECCurveFp: ECCurveFp
  1109. };
  1110. /***/ }),
  1111. /* 7 */
  1112. /***/ (function(module, exports, __webpack_require__) {
  1113. "use strict";
  1114. var _require = __webpack_require__(1),
  1115. sm3 = _require.sm3,
  1116. hmac = _require.hmac;
  1117. /**
  1118. * 补全16进制字符串
  1119. */
  1120. function leftPad(input, num) {
  1121. if (input.length >= num) return input;
  1122. return new Array(num - input.length + 1).join('0') + input;
  1123. }
  1124. /**
  1125. * 字节数组转 16 进制串
  1126. */
  1127. function ArrayToHex(arr) {
  1128. return arr.map(function (item) {
  1129. item = item.toString(16);
  1130. return item.length === 1 ? '0' + item : item;
  1131. }).join('');
  1132. }
  1133. /**
  1134. * 转成字节数组
  1135. */
  1136. function hexToArray(hexStr) {
  1137. var words = [];
  1138. var hexStrLength = hexStr.length;
  1139. if (hexStrLength % 2 !== 0) {
  1140. hexStr = leftPad(hexStr, hexStrLength + 1);
  1141. }
  1142. hexStrLength = hexStr.length;
  1143. for (var i = 0; i < hexStrLength; i += 2) {
  1144. words.push(parseInt(hexStr.substr(i, 2), 16));
  1145. }
  1146. return words;
  1147. }
  1148. /**
  1149. * utf8 串转字节数组
  1150. */
  1151. function utf8ToArray(str) {
  1152. var arr = [];
  1153. for (var i = 0, len = str.length; i < len; i++) {
  1154. var point = str.codePointAt(i);
  1155. if (point <= 0x007f) {
  1156. // 单字节,标量值:00000000 00000000 0zzzzzzz
  1157. arr.push(point);
  1158. } else if (point <= 0x07ff) {
  1159. // 双字节,标量值:00000000 00000yyy yyzzzzzz
  1160. arr.push(0xc0 | point >>> 6); // 110yyyyy(0xc0-0xdf)
  1161. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1162. } else if (point <= 0xD7FF || point >= 0xE000 && point <= 0xFFFF) {
  1163. // 三字节:标量值:00000000 xxxxyyyy yyzzzzzz
  1164. arr.push(0xe0 | point >>> 12); // 1110xxxx(0xe0-0xef)
  1165. arr.push(0x80 | point >>> 6 & 0x3f); // 10yyyyyy(0x80-0xbf)
  1166. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1167. } else if (point >= 0x010000 && point <= 0x10FFFF) {
  1168. // 四字节:标量值:000wwwxx xxxxyyyy yyzzzzzz
  1169. i++;
  1170. arr.push(0xf0 | point >>> 18 & 0x1c); // 11110www(0xf0-0xf7)
  1171. arr.push(0x80 | point >>> 12 & 0x3f); // 10xxxxxx(0x80-0xbf)
  1172. arr.push(0x80 | point >>> 6 & 0x3f); // 10yyyyyy(0x80-0xbf)
  1173. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1174. } else {
  1175. // 五、六字节,暂时不支持
  1176. arr.push(point);
  1177. throw new Error('input is not supported');
  1178. }
  1179. }
  1180. return arr;
  1181. }
  1182. module.exports = function (input, options) {
  1183. input = typeof input === 'string' ? utf8ToArray(input) : Array.prototype.slice.call(input);
  1184. if (options) {
  1185. var mode = options.mode || 'hmac';
  1186. if (mode !== 'hmac') throw new Error('invalid mode');
  1187. var key = options.key;
  1188. if (!key) throw new Error('invalid key');
  1189. key = typeof key === 'string' ? hexToArray(key) : Array.prototype.slice.call(key);
  1190. return ArrayToHex(hmac(input, key));
  1191. }
  1192. return ArrayToHex(sm3(input));
  1193. };
  1194. /***/ }),
  1195. /* 8 */
  1196. /***/ (function(module, exports, __webpack_require__) {
  1197. "use strict";
  1198. /* eslint-disable no-bitwise, no-mixed-operators, complexity */
  1199. var DECRYPT = 0;
  1200. var ROUND = 32;
  1201. var BLOCK = 16;
  1202. var Sbox = [0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05, 0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99, 0x9c, 0x42, 0x50, 0xf4, 0x91, 0xef, 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43, 0xed, 0xcf, 0xac, 0x62, 0xe4, 0xb3, 0x1c, 0xa9, 0xc9, 0x08, 0xe8, 0x95, 0x80, 0xdf, 0x94, 0xfa, 0x75, 0x8f, 0x3f, 0xa6, 0x47, 0x07, 0xa7, 0xfc, 0xf3, 0x73, 0x17, 0xba, 0x83, 0x59, 0x3c, 0x19, 0xe6, 0x85, 0x4f, 0xa8, 0x68, 0x6b, 0x81, 0xb2, 0x71, 0x64, 0xda, 0x8b, 0xf8, 0xeb, 0x0f, 0x4b, 0x70, 0x56, 0x9d, 0x35, 0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, 0xd1, 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, 0x87, 0xd4, 0x00, 0x46, 0x57, 0x9f, 0xd3, 0x27, 0x52, 0x4c, 0x36, 0x02, 0xe7, 0xa0, 0xc4, 0xc8, 0x9e, 0xea, 0xbf, 0x8a, 0xd2, 0x40, 0xc7, 0x38, 0xb5, 0xa3, 0xf7, 0xf2, 0xce, 0xf9, 0x61, 0x15, 0xa1, 0xe0, 0xae, 0x5d, 0xa4, 0x9b, 0x34, 0x1a, 0x55, 0xad, 0x93, 0x32, 0x30, 0xf5, 0x8c, 0xb1, 0xe3, 0x1d, 0xf6, 0xe2, 0x2e, 0x82, 0x66, 0xca, 0x60, 0xc0, 0x29, 0x23, 0xab, 0x0d, 0x53, 0x4e, 0x6f, 0xd5, 0xdb, 0x37, 0x45, 0xde, 0xfd, 0x8e, 0x2f, 0x03, 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b, 0x51, 0x8d, 0x1b, 0xaf, 0x92, 0xbb, 0xdd, 0xbc, 0x7f, 0x11, 0xd9, 0x5c, 0x41, 0x1f, 0x10, 0x5a, 0xd8, 0x0a, 0xc1, 0x31, 0x88, 0xa5, 0xcd, 0x7b, 0xbd, 0x2d, 0x74, 0xd0, 0x12, 0xb8, 0xe5, 0xb4, 0xb0, 0x89, 0x69, 0x97, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0xb9, 0xf1, 0x09, 0xc5, 0x6e, 0xc6, 0x84, 0x18, 0xf0, 0x7d, 0xec, 0x3a, 0xdc, 0x4d, 0x20, 0x79, 0xee, 0x5f, 0x3e, 0xd7, 0xcb, 0x39, 0x48];
  1203. var CK = [0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269, 0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9, 0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249, 0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9, 0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229, 0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299, 0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209, 0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279];
  1204. /**
  1205. * 16 进制串转字节数组
  1206. */
  1207. function hexToArray(str) {
  1208. var arr = [];
  1209. for (var i = 0, len = str.length; i < len; i += 2) {
  1210. arr.push(parseInt(str.substr(i, 2), 16));
  1211. }
  1212. return arr;
  1213. }
  1214. /**
  1215. * 字节数组转 16 进制串
  1216. */
  1217. function ArrayToHex(arr) {
  1218. return arr.map(function (item) {
  1219. item = item.toString(16);
  1220. return item.length === 1 ? '0' + item : item;
  1221. }).join('');
  1222. }
  1223. /**
  1224. * utf8 串转字节数组
  1225. */
  1226. function utf8ToArray(str) {
  1227. var arr = [];
  1228. for (var i = 0, len = str.length; i < len; i++) {
  1229. var point = str.codePointAt(i);
  1230. if (point <= 0x007f) {
  1231. // 单字节,标量值:00000000 00000000 0zzzzzzz
  1232. arr.push(point);
  1233. } else if (point <= 0x07ff) {
  1234. // 双字节,标量值:00000000 00000yyy yyzzzzzz
  1235. arr.push(0xc0 | point >>> 6); // 110yyyyy(0xc0-0xdf)
  1236. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1237. } else if (point <= 0xD7FF || point >= 0xE000 && point <= 0xFFFF) {
  1238. // 三字节:标量值:00000000 xxxxyyyy yyzzzzzz
  1239. arr.push(0xe0 | point >>> 12); // 1110xxxx(0xe0-0xef)
  1240. arr.push(0x80 | point >>> 6 & 0x3f); // 10yyyyyy(0x80-0xbf)
  1241. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1242. } else if (point >= 0x010000 && point <= 0x10FFFF) {
  1243. // 四字节:标量值:000wwwxx xxxxyyyy yyzzzzzz
  1244. i++;
  1245. arr.push(0xf0 | point >>> 18 & 0x1c); // 11110www(0xf0-0xf7)
  1246. arr.push(0x80 | point >>> 12 & 0x3f); // 10xxxxxx(0x80-0xbf)
  1247. arr.push(0x80 | point >>> 6 & 0x3f); // 10yyyyyy(0x80-0xbf)
  1248. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1249. } else {
  1250. // 五、六字节,暂时不支持
  1251. arr.push(point);
  1252. throw new Error('input is not supported');
  1253. }
  1254. }
  1255. return arr;
  1256. }
  1257. /**
  1258. * 字节数组转 utf8 串
  1259. */
  1260. function arrayToUtf8(arr) {
  1261. var str = [];
  1262. for (var i = 0, len = arr.length; i < len; i++) {
  1263. if (arr[i] >= 0xf0 && arr[i] <= 0xf7) {
  1264. // 四字节
  1265. str.push(String.fromCodePoint(((arr[i] & 0x07) << 18) + ((arr[i + 1] & 0x3f) << 12) + ((arr[i + 2] & 0x3f) << 6) + (arr[i + 3] & 0x3f)));
  1266. i += 3;
  1267. } else if (arr[i] >= 0xe0 && arr[i] <= 0xef) {
  1268. // 三字节
  1269. str.push(String.fromCodePoint(((arr[i] & 0x0f) << 12) + ((arr[i + 1] & 0x3f) << 6) + (arr[i + 2] & 0x3f)));
  1270. i += 2;
  1271. } else if (arr[i] >= 0xc0 && arr[i] <= 0xdf) {
  1272. // 双字节
  1273. str.push(String.fromCodePoint(((arr[i] & 0x1f) << 6) + (arr[i + 1] & 0x3f)));
  1274. i++;
  1275. } else {
  1276. // 单字节
  1277. str.push(String.fromCodePoint(arr[i]));
  1278. }
  1279. }
  1280. return str.join('');
  1281. }
  1282. /**
  1283. * 32 比特循环左移
  1284. */
  1285. function rotl(x, n) {
  1286. var s = n & 31;
  1287. return x << s | x >>> 32 - s;
  1288. }
  1289. /**
  1290. * 非线性变换
  1291. */
  1292. function byteSub(a) {
  1293. return (Sbox[a >>> 24 & 0xFF] & 0xFF) << 24 | (Sbox[a >>> 16 & 0xFF] & 0xFF) << 16 | (Sbox[a >>> 8 & 0xFF] & 0xFF) << 8 | Sbox[a & 0xFF] & 0xFF;
  1294. }
  1295. /**
  1296. * 线性变换,加密/解密用
  1297. */
  1298. function l1(b) {
  1299. return b ^ rotl(b, 2) ^ rotl(b, 10) ^ rotl(b, 18) ^ rotl(b, 24);
  1300. }
  1301. /**
  1302. * 线性变换,生成轮密钥用
  1303. */
  1304. function l2(b) {
  1305. return b ^ rotl(b, 13) ^ rotl(b, 23);
  1306. }
  1307. /**
  1308. * 以一组 128 比特进行加密/解密操作
  1309. */
  1310. function sms4Crypt(input, output, roundKey) {
  1311. var x = new Array(4);
  1312. // 字节数组转成字数组(此处 1 字 = 32 比特)
  1313. var tmp = new Array(4);
  1314. for (var i = 0; i < 4; i++) {
  1315. tmp[0] = input[4 * i] & 0xff;
  1316. tmp[1] = input[4 * i + 1] & 0xff;
  1317. tmp[2] = input[4 * i + 2] & 0xff;
  1318. tmp[3] = input[4 * i + 3] & 0xff;
  1319. x[i] = tmp[0] << 24 | tmp[1] << 16 | tmp[2] << 8 | tmp[3];
  1320. }
  1321. // x[i + 4] = x[i] ^ l1(byteSub(x[i + 1] ^ x[i + 2] ^ x[i + 3] ^ roundKey[i]))
  1322. for (var r = 0, mid; r < 32; r += 4) {
  1323. mid = x[1] ^ x[2] ^ x[3] ^ roundKey[r + 0];
  1324. x[0] ^= l1(byteSub(mid)); // x[4]
  1325. mid = x[2] ^ x[3] ^ x[0] ^ roundKey[r + 1];
  1326. x[1] ^= l1(byteSub(mid)); // x[5]
  1327. mid = x[3] ^ x[0] ^ x[1] ^ roundKey[r + 2];
  1328. x[2] ^= l1(byteSub(mid)); // x[6]
  1329. mid = x[0] ^ x[1] ^ x[2] ^ roundKey[r + 3];
  1330. x[3] ^= l1(byteSub(mid)); // x[7]
  1331. }
  1332. // 反序变换
  1333. for (var j = 0; j < 16; j += 4) {
  1334. output[j] = x[3 - j / 4] >>> 24 & 0xff;
  1335. output[j + 1] = x[3 - j / 4] >>> 16 & 0xff;
  1336. output[j + 2] = x[3 - j / 4] >>> 8 & 0xff;
  1337. output[j + 3] = x[3 - j / 4] & 0xff;
  1338. }
  1339. }
  1340. /**
  1341. * 密钥扩展算法
  1342. */
  1343. function sms4KeyExt(key, roundKey, cryptFlag) {
  1344. var x = new Array(4);
  1345. // 字节数组转成字数组(此处 1 字 = 32 比特)
  1346. var tmp = new Array(4);
  1347. for (var i = 0; i < 4; i++) {
  1348. tmp[0] = key[0 + 4 * i] & 0xff;
  1349. tmp[1] = key[1 + 4 * i] & 0xff;
  1350. tmp[2] = key[2 + 4 * i] & 0xff;
  1351. tmp[3] = key[3 + 4 * i] & 0xff;
  1352. x[i] = tmp[0] << 24 | tmp[1] << 16 | tmp[2] << 8 | tmp[3];
  1353. }
  1354. // 与系统参数做异或
  1355. x[0] ^= 0xa3b1bac6;
  1356. x[1] ^= 0x56aa3350;
  1357. x[2] ^= 0x677d9197;
  1358. x[3] ^= 0xb27022dc;
  1359. // roundKey[i] = x[i + 4] = x[i] ^ l2(byteSub(x[i + 1] ^ x[i + 2] ^ x[i + 3] ^ CK[i]))
  1360. for (var r = 0, mid; r < 32; r += 4) {
  1361. mid = x[1] ^ x[2] ^ x[3] ^ CK[r + 0];
  1362. roundKey[r + 0] = x[0] ^= l2(byteSub(mid)); // x[4]
  1363. mid = x[2] ^ x[3] ^ x[0] ^ CK[r + 1];
  1364. roundKey[r + 1] = x[1] ^= l2(byteSub(mid)); // x[5]
  1365. mid = x[3] ^ x[0] ^ x[1] ^ CK[r + 2];
  1366. roundKey[r + 2] = x[2] ^= l2(byteSub(mid)); // x[6]
  1367. mid = x[0] ^ x[1] ^ x[2] ^ CK[r + 3];
  1368. roundKey[r + 3] = x[3] ^= l2(byteSub(mid)); // x[7]
  1369. }
  1370. // 解密时使用反序的轮密钥
  1371. if (cryptFlag === DECRYPT) {
  1372. for (var _r = 0, _mid; _r < 16; _r++) {
  1373. _mid = roundKey[_r];
  1374. roundKey[_r] = roundKey[31 - _r];
  1375. roundKey[31 - _r] = _mid;
  1376. }
  1377. }
  1378. }
  1379. function sm4(inArray, key, cryptFlag) {
  1380. var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {},
  1381. _ref$padding = _ref.padding,
  1382. padding = _ref$padding === undefined ? 'pkcs#7' : _ref$padding,
  1383. mode = _ref.mode,
  1384. _ref$iv = _ref.iv,
  1385. iv = _ref$iv === undefined ? [] : _ref$iv,
  1386. _ref$output = _ref.output,
  1387. output = _ref$output === undefined ? 'string' : _ref$output;
  1388. if (mode === 'cbc') {
  1389. // CBC 模式,默认走 ECB 模式
  1390. if (typeof iv === 'string') iv = hexToArray(iv);
  1391. if (iv.length !== 128 / 8) {
  1392. // iv 不是 128 比特
  1393. throw new Error('iv is invalid');
  1394. }
  1395. }
  1396. // 检查 key
  1397. if (typeof key === 'string') key = hexToArray(key);
  1398. if (key.length !== 128 / 8) {
  1399. // key 不是 128 比特
  1400. throw new Error('key is invalid');
  1401. }
  1402. // 检查输入
  1403. if (typeof inArray === 'string') {
  1404. if (cryptFlag !== DECRYPT) {
  1405. // 加密,输入为 utf8 串
  1406. inArray = utf8ToArray(inArray);
  1407. } else {
  1408. // 解密,输入为 16 进制串
  1409. inArray = hexToArray(inArray);
  1410. }
  1411. } else {
  1412. inArray = [].concat(inArray);
  1413. }
  1414. // 新增填充,sm4 是 16 个字节一个分组,所以统一走到 pkcs#7
  1415. if ((padding === 'pkcs#5' || padding === 'pkcs#7') && cryptFlag !== DECRYPT) {
  1416. var paddingCount = BLOCK - inArray.length % BLOCK;
  1417. for (var i = 0; i < paddingCount; i++) {
  1418. inArray.push(paddingCount);
  1419. }
  1420. }
  1421. // 生成轮密钥
  1422. var roundKey = new Array(ROUND);
  1423. sms4KeyExt(key, roundKey, cryptFlag);
  1424. var outArray = [];
  1425. var lastVector = iv;
  1426. var restLen = inArray.length;
  1427. var point = 0;
  1428. while (restLen >= BLOCK) {
  1429. var input = inArray.slice(point, point + 16);
  1430. var _output = new Array(16);
  1431. if (mode === 'cbc') {
  1432. for (var _i = 0; _i < BLOCK; _i++) {
  1433. if (cryptFlag !== DECRYPT) {
  1434. // 加密过程在组加密前进行异或
  1435. input[_i] ^= lastVector[_i];
  1436. }
  1437. }
  1438. }
  1439. sms4Crypt(input, _output, roundKey);
  1440. for (var _i2 = 0; _i2 < BLOCK; _i2++) {
  1441. if (mode === 'cbc') {
  1442. if (cryptFlag === DECRYPT) {
  1443. // 解密过程在组解密后进行异或
  1444. _output[_i2] ^= lastVector[_i2];
  1445. }
  1446. }
  1447. outArray[point + _i2] = _output[_i2];
  1448. }
  1449. if (mode === 'cbc') {
  1450. if (cryptFlag !== DECRYPT) {
  1451. // 使用上一次输出作为加密向量
  1452. lastVector = _output;
  1453. } else {
  1454. // 使用上一次输入作为解密向量
  1455. lastVector = input;
  1456. }
  1457. }
  1458. restLen -= BLOCK;
  1459. point += BLOCK;
  1460. }
  1461. // 去除填充,sm4 是 16 个字节一个分组,所以统一走到 pkcs#7
  1462. if ((padding === 'pkcs#5' || padding === 'pkcs#7') && cryptFlag === DECRYPT) {
  1463. var len = outArray.length;
  1464. var _paddingCount = outArray[len - 1];
  1465. for (var _i3 = 1; _i3 <= _paddingCount; _i3++) {
  1466. if (outArray[len - _i3] !== _paddingCount) throw new Error('padding is invalid');
  1467. }
  1468. outArray.splice(len - _paddingCount, _paddingCount);
  1469. }
  1470. // 调整输出
  1471. if (output !== 'array') {
  1472. if (cryptFlag !== DECRYPT) {
  1473. // 加密,输出转 16 进制串
  1474. return ArrayToHex(outArray);
  1475. } else {
  1476. // 解密,输出转 utf8 串
  1477. return arrayToUtf8(outArray);
  1478. }
  1479. } else {
  1480. return outArray;
  1481. }
  1482. }
  1483. module.exports = {
  1484. encrypt: function encrypt(inArray, key, options) {
  1485. return sm4(inArray, key, 1, options);
  1486. },
  1487. decrypt: function decrypt(inArray, key, options) {
  1488. return sm4(inArray, key, 0, options);
  1489. }
  1490. };
  1491. /***/ })
  1492. /******/ ]);