index.js 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835
  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. getPoint: getPoint,
  490. verifyPublicKey: _.verifyPublicKey
  491. };
  492. /***/ }),
  493. /* 4 */
  494. /***/ (function(module, exports, __webpack_require__) {
  495. "use strict";
  496. 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; }
  497. 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; }
  498. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  499. /* eslint-disable class-methods-use-this */
  500. var _require = __webpack_require__(0),
  501. BigInteger = _require.BigInteger;
  502. function bigintToValue(bigint) {
  503. var h = bigint.toString(16);
  504. if (h[0] !== '-') {
  505. // 正数
  506. if (h.length % 2 === 1) h = '0' + h; // 补齐到整字节
  507. else if (!h.match(/^[0-7]/)) h = '00' + h; // 非0开头,则补一个全0字节
  508. } else {
  509. // 负数
  510. h = h.substr(1);
  511. var len = h.length;
  512. if (len % 2 === 1) len += 1; // 补齐到整字节
  513. else if (!h.match(/^[0-7]/)) len += 2; // 非0开头,则补一个全0字节
  514. var mask = '';
  515. for (var i = 0; i < len; i++) {
  516. mask += 'f';
  517. }mask = new BigInteger(mask, 16);
  518. // 对绝对值取反,加1
  519. h = mask.xor(bigint).add(BigInteger.ONE);
  520. h = h.toString(16).replace(/^-/, '');
  521. }
  522. return h;
  523. }
  524. var ASN1Object = function () {
  525. function ASN1Object() {
  526. _classCallCheck(this, ASN1Object);
  527. this.tlv = null;
  528. this.t = '00';
  529. this.l = '00';
  530. this.v = '';
  531. }
  532. /**
  533. * 获取 der 编码比特流16进制串
  534. */
  535. ASN1Object.prototype.getEncodedHex = function getEncodedHex() {
  536. if (!this.tlv) {
  537. this.v = this.getValue();
  538. this.l = this.getLength();
  539. this.tlv = this.t + this.l + this.v;
  540. }
  541. return this.tlv;
  542. };
  543. ASN1Object.prototype.getLength = function getLength() {
  544. var n = this.v.length / 2; // 字节数
  545. var nHex = n.toString(16);
  546. if (nHex.length % 2 === 1) nHex = '0' + nHex; // 补齐到整字节
  547. if (n < 128) {
  548. // 短格式,以 0 开头
  549. return nHex;
  550. } else {
  551. // 长格式,以 1 开头
  552. var head = 128 + nHex.length / 2; // 1(1位) + 真正的长度占用字节数(7位) + 真正的长度
  553. return head.toString(16) + nHex;
  554. }
  555. };
  556. ASN1Object.prototype.getValue = function getValue() {
  557. return '';
  558. };
  559. return ASN1Object;
  560. }();
  561. var DERInteger = function (_ASN1Object) {
  562. _inherits(DERInteger, _ASN1Object);
  563. function DERInteger(bigint) {
  564. _classCallCheck(this, DERInteger);
  565. var _this = _possibleConstructorReturn(this, _ASN1Object.call(this));
  566. _this.t = '02'; // 整型标签说明
  567. if (bigint) _this.v = bigintToValue(bigint);
  568. return _this;
  569. }
  570. DERInteger.prototype.getValue = function getValue() {
  571. return this.v;
  572. };
  573. return DERInteger;
  574. }(ASN1Object);
  575. var DERSequence = function (_ASN1Object2) {
  576. _inherits(DERSequence, _ASN1Object2);
  577. function DERSequence(asn1Array) {
  578. _classCallCheck(this, DERSequence);
  579. var _this2 = _possibleConstructorReturn(this, _ASN1Object2.call(this));
  580. _this2.t = '30'; // 序列标签说明
  581. _this2.asn1Array = asn1Array;
  582. return _this2;
  583. }
  584. DERSequence.prototype.getValue = function getValue() {
  585. this.v = this.asn1Array.map(function (asn1Object) {
  586. return asn1Object.getEncodedHex();
  587. }).join('');
  588. return this.v;
  589. };
  590. return DERSequence;
  591. }(ASN1Object);
  592. /**
  593. * 获取 l 占用字节数
  594. */
  595. function getLenOfL(str, start) {
  596. if (+str[start + 2] < 8) return 1; // l 以0开头,则表示短格式,只占一个字节
  597. return +str.substr(start + 2, 2) & 0x7f + 1; // 长格式,取第一个字节后7位作为长度真正占用字节数,再加上本身
  598. }
  599. /**
  600. * 获取 l
  601. */
  602. function getL(str, start) {
  603. // 获取 l
  604. var len = getLenOfL(str, start);
  605. var l = str.substr(start + 2, len * 2);
  606. if (!l) return -1;
  607. var bigint = +l[0] < 8 ? new BigInteger(l, 16) : new BigInteger(l.substr(2), 16);
  608. return bigint.intValue();
  609. }
  610. /**
  611. * 获取 v 的位置
  612. */
  613. function getStartOfV(str, start) {
  614. var len = getLenOfL(str, start);
  615. return start + (len + 1) * 2;
  616. }
  617. module.exports = {
  618. /**
  619. * ASN.1 der 编码,针对 sm2 签名
  620. */
  621. encodeDer: function encodeDer(r, s) {
  622. var derR = new DERInteger(r);
  623. var derS = new DERInteger(s);
  624. var derSeq = new DERSequence([derR, derS]);
  625. return derSeq.getEncodedHex();
  626. },
  627. /**
  628. * 解析 ASN.1 der,针对 sm2 验签
  629. */
  630. decodeDer: function decodeDer(input) {
  631. // 结构:
  632. // input = | tSeq | lSeq | vSeq |
  633. // vSeq = | tR | lR | vR | tS | lS | vS |
  634. var start = getStartOfV(input, 0);
  635. var vIndexR = getStartOfV(input, start);
  636. var lR = getL(input, start);
  637. var vR = input.substr(vIndexR, lR * 2);
  638. var nextStart = vIndexR + vR.length;
  639. var vIndexS = getStartOfV(input, nextStart);
  640. var lS = getL(input, nextStart);
  641. var vS = input.substr(vIndexS, lS * 2);
  642. var r = new BigInteger(vR, 16);
  643. var s = new BigInteger(vS, 16);
  644. return { r: r, s: s };
  645. }
  646. };
  647. /***/ }),
  648. /* 5 */
  649. /***/ (function(module, exports, __webpack_require__) {
  650. "use strict";
  651. /* eslint-disable no-bitwise, no-mixed-operators, no-use-before-define, max-len */
  652. var _require = __webpack_require__(0),
  653. BigInteger = _require.BigInteger,
  654. SecureRandom = _require.SecureRandom;
  655. var _require2 = __webpack_require__(6),
  656. ECCurveFp = _require2.ECCurveFp;
  657. var rng = new SecureRandom();
  658. var _generateEcparam = generateEcparam(),
  659. curve = _generateEcparam.curve,
  660. G = _generateEcparam.G,
  661. n = _generateEcparam.n;
  662. /**
  663. * 获取公共椭圆曲线
  664. */
  665. function getGlobalCurve() {
  666. return curve;
  667. }
  668. /**
  669. * 生成ecparam
  670. */
  671. function generateEcparam() {
  672. // 椭圆曲线
  673. var p = new BigInteger('FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF', 16);
  674. var a = new BigInteger('FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC', 16);
  675. var b = new BigInteger('28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93', 16);
  676. var curve = new ECCurveFp(p, a, b);
  677. // 基点
  678. var gxHex = '32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7';
  679. var gyHex = 'BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0';
  680. var G = curve.decodePointHex('04' + gxHex + gyHex);
  681. var n = new BigInteger('FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123', 16);
  682. return { curve: curve, G: G, n: n };
  683. }
  684. /**
  685. * 生成密钥对:publicKey = privateKey * G
  686. */
  687. function generateKeyPairHex(a, b, c) {
  688. var random = a ? new BigInteger(a, b, c) : new BigInteger(n.bitLength(), rng);
  689. var d = random.mod(n.subtract(BigInteger.ONE)).add(BigInteger.ONE); // 随机数
  690. var privateKey = leftPad(d.toString(16), 64);
  691. var P = G.multiply(d); // P = dG,p 为公钥,d 为私钥
  692. var Px = leftPad(P.getX().toBigInteger().toString(16), 64);
  693. var Py = leftPad(P.getY().toBigInteger().toString(16), 64);
  694. var publicKey = '04' + Px + Py;
  695. return { privateKey: privateKey, publicKey: publicKey };
  696. }
  697. /**
  698. * 生成压缩公钥
  699. */
  700. function compressPublicKeyHex(s) {
  701. if (s.length !== 130) throw new Error('Invalid public key to compress');
  702. var len = (s.length - 2) / 2;
  703. var xHex = s.substr(2, len);
  704. var y = new BigInteger(s.substr(len + 2, len), 16);
  705. var prefix = '03';
  706. if (y.mod(new BigInteger('2')).equals(BigInteger.ZERO)) prefix = '02';
  707. return prefix + xHex;
  708. }
  709. /**
  710. * utf8串转16进制串
  711. */
  712. function utf8ToHex(input) {
  713. input = unescape(encodeURIComponent(input));
  714. var length = input.length;
  715. // 转换到字数组
  716. var words = [];
  717. for (var i = 0; i < length; i++) {
  718. words[i >>> 2] |= (input.charCodeAt(i) & 0xff) << 24 - i % 4 * 8;
  719. }
  720. // 转换到16进制
  721. var hexChars = [];
  722. for (var _i = 0; _i < length; _i++) {
  723. var bite = words[_i >>> 2] >>> 24 - _i % 4 * 8 & 0xff;
  724. hexChars.push((bite >>> 4).toString(16));
  725. hexChars.push((bite & 0x0f).toString(16));
  726. }
  727. return hexChars.join('');
  728. }
  729. /**
  730. * 补全16进制字符串
  731. */
  732. function leftPad(input, num) {
  733. if (input.length >= num) return input;
  734. return new Array(num - input.length + 1).join('0') + input;
  735. }
  736. /**
  737. * 转成16进制串
  738. */
  739. function arrayToHex(arr) {
  740. return arr.map(function (item) {
  741. item = item.toString(16);
  742. return item.length === 1 ? '0' + item : item;
  743. }).join('');
  744. }
  745. /**
  746. * 转成utf8串
  747. */
  748. function arrayToUtf8(arr) {
  749. var words = [];
  750. var j = 0;
  751. for (var i = 0; i < arr.length * 2; i += 2) {
  752. words[i >>> 3] |= parseInt(arr[j], 10) << 24 - i % 8 * 4;
  753. j++;
  754. }
  755. try {
  756. var latin1Chars = [];
  757. for (var _i2 = 0; _i2 < arr.length; _i2++) {
  758. var bite = words[_i2 >>> 2] >>> 24 - _i2 % 4 * 8 & 0xff;
  759. latin1Chars.push(String.fromCharCode(bite));
  760. }
  761. return decodeURIComponent(escape(latin1Chars.join('')));
  762. } catch (e) {
  763. throw new Error('Malformed UTF-8 data');
  764. }
  765. }
  766. /**
  767. * 转成字节数组
  768. */
  769. function hexToArray(hexStr) {
  770. var words = [];
  771. var hexStrLength = hexStr.length;
  772. if (hexStrLength % 2 !== 0) {
  773. hexStr = leftPad(hexStr, hexStrLength + 1);
  774. }
  775. hexStrLength = hexStr.length;
  776. for (var i = 0; i < hexStrLength; i += 2) {
  777. words.push(parseInt(hexStr.substr(i, 2), 16));
  778. }
  779. return words;
  780. }
  781. /**
  782. * 验证公钥是否为椭圆曲线上的点
  783. */
  784. function verifyPublicKey(publicKey) {
  785. var point = curve.decodePointHex(publicKey);
  786. if (!point) return false;
  787. var x = point.getX();
  788. var y = point.getY();
  789. // 验证 y^2 是否等于 x^3 + ax + b
  790. return y.square().equals(x.multiply(x.square()).add(x.multiply(curve.a)).add(curve.b));
  791. }
  792. /**
  793. * 验证公钥是否等价,等价返回true
  794. */
  795. function comparePublicKeyHex(publicKey1, publicKey2) {
  796. var point1 = curve.decodePointHex(publicKey1);
  797. if (!point1) return false;
  798. var point2 = curve.decodePointHex(publicKey2);
  799. if (!point2) return false;
  800. return point1.equals(point2);
  801. }
  802. module.exports = {
  803. getGlobalCurve: getGlobalCurve,
  804. generateEcparam: generateEcparam,
  805. generateKeyPairHex: generateKeyPairHex,
  806. compressPublicKeyHex: compressPublicKeyHex,
  807. utf8ToHex: utf8ToHex,
  808. leftPad: leftPad,
  809. arrayToHex: arrayToHex,
  810. arrayToUtf8: arrayToUtf8,
  811. hexToArray: hexToArray,
  812. verifyPublicKey: verifyPublicKey,
  813. comparePublicKeyHex: comparePublicKeyHex
  814. };
  815. /***/ }),
  816. /* 6 */
  817. /***/ (function(module, exports, __webpack_require__) {
  818. "use strict";
  819. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  820. /* eslint-disable no-case-declarations, max-len */
  821. var _require = __webpack_require__(0),
  822. BigInteger = _require.BigInteger;
  823. /**
  824. * thanks for Tom Wu : http://www-cs-students.stanford.edu/~tjw/jsbn/
  825. *
  826. * Basic Javascript Elliptic Curve implementation
  827. * Ported loosely from BouncyCastle's Java EC code
  828. * Only Fp curves implemented for now
  829. */
  830. var TWO = new BigInteger('2');
  831. var THREE = new BigInteger('3');
  832. /**
  833. * 椭圆曲线域元素
  834. */
  835. var ECFieldElementFp = function () {
  836. function ECFieldElementFp(q, x) {
  837. _classCallCheck(this, ECFieldElementFp);
  838. this.x = x;
  839. this.q = q;
  840. // TODO if (x.compareTo(q) >= 0) error
  841. }
  842. /**
  843. * 判断相等
  844. */
  845. ECFieldElementFp.prototype.equals = function equals(other) {
  846. if (other === this) return true;
  847. return this.q.equals(other.q) && this.x.equals(other.x);
  848. };
  849. /**
  850. * 返回具体数值
  851. */
  852. ECFieldElementFp.prototype.toBigInteger = function toBigInteger() {
  853. return this.x;
  854. };
  855. /**
  856. * 取反
  857. */
  858. ECFieldElementFp.prototype.negate = function negate() {
  859. return new ECFieldElementFp(this.q, this.x.negate().mod(this.q));
  860. };
  861. /**
  862. * 相加
  863. */
  864. ECFieldElementFp.prototype.add = function add(b) {
  865. return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q));
  866. };
  867. /**
  868. * 相减
  869. */
  870. ECFieldElementFp.prototype.subtract = function subtract(b) {
  871. return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q));
  872. };
  873. /**
  874. * 相乘
  875. */
  876. ECFieldElementFp.prototype.multiply = function multiply(b) {
  877. return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q));
  878. };
  879. /**
  880. * 相除
  881. */
  882. ECFieldElementFp.prototype.divide = function divide(b) {
  883. return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q));
  884. };
  885. /**
  886. * 平方
  887. */
  888. ECFieldElementFp.prototype.square = function square() {
  889. return new ECFieldElementFp(this.q, this.x.square().mod(this.q));
  890. };
  891. return ECFieldElementFp;
  892. }();
  893. var ECPointFp = function () {
  894. function ECPointFp(curve, x, y, z) {
  895. _classCallCheck(this, ECPointFp);
  896. this.curve = curve;
  897. this.x = x;
  898. this.y = y;
  899. // 标准射影坐标系:zinv == null 或 z * zinv == 1
  900. this.z = z == null ? BigInteger.ONE : z;
  901. this.zinv = null;
  902. // TODO: compression flag
  903. }
  904. ECPointFp.prototype.getX = function getX() {
  905. if (this.zinv === null) this.zinv = this.z.modInverse(this.curve.q);
  906. return this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q));
  907. };
  908. ECPointFp.prototype.getY = function getY() {
  909. if (this.zinv === null) this.zinv = this.z.modInverse(this.curve.q);
  910. return this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q));
  911. };
  912. /**
  913. * 判断相等
  914. */
  915. ECPointFp.prototype.equals = function equals(other) {
  916. if (other === this) return true;
  917. if (this.isInfinity()) return other.isInfinity();
  918. if (other.isInfinity()) return this.isInfinity();
  919. // u = y2 * z1 - y1 * z2
  920. var u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q);
  921. if (!u.equals(BigInteger.ZERO)) return false;
  922. // v = x2 * z1 - x1 * z2
  923. var v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q);
  924. return v.equals(BigInteger.ZERO);
  925. };
  926. /**
  927. * 是否是无穷远点
  928. */
  929. ECPointFp.prototype.isInfinity = function isInfinity() {
  930. if (this.x === null && this.y === null) return true;
  931. return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO);
  932. };
  933. /**
  934. * 取反,x 轴对称点
  935. */
  936. ECPointFp.prototype.negate = function negate() {
  937. return new ECPointFp(this.curve, this.x, this.y.negate(), this.z);
  938. };
  939. /**
  940. * 相加
  941. *
  942. * 标准射影坐标系:
  943. *
  944. * λ1 = x1 * z2
  945. * λ2 = x2 * z1
  946. * λ3 = λ1 − λ2
  947. * λ4 = y1 * z2
  948. * λ5 = y2 * z1
  949. * λ6 = λ4 − λ5
  950. * λ7 = λ1 + λ2
  951. * λ8 = z1 * z2
  952. * λ9 = λ3^2
  953. * λ10 = λ3 * λ9
  954. * λ11 = λ8 * λ6^2 − λ7 * λ9
  955. * x3 = λ3 * λ11
  956. * y3 = λ6 * (λ9 * λ1 − λ11) − λ4 * λ10
  957. * z3 = λ10 * λ8
  958. */
  959. ECPointFp.prototype.add = function add(b) {
  960. if (this.isInfinity()) return b;
  961. if (b.isInfinity()) return this;
  962. var x1 = this.x.toBigInteger();
  963. var y1 = this.y.toBigInteger();
  964. var z1 = this.z;
  965. var x2 = b.x.toBigInteger();
  966. var y2 = b.y.toBigInteger();
  967. var z2 = b.z;
  968. var q = this.curve.q;
  969. var w1 = x1.multiply(z2).mod(q);
  970. var w2 = x2.multiply(z1).mod(q);
  971. var w3 = w1.subtract(w2);
  972. var w4 = y1.multiply(z2).mod(q);
  973. var w5 = y2.multiply(z1).mod(q);
  974. var w6 = w4.subtract(w5);
  975. if (BigInteger.ZERO.equals(w3)) {
  976. if (BigInteger.ZERO.equals(w6)) {
  977. return this.twice(); // this == b,计算自加
  978. }
  979. return this.curve.infinity; // this == -b,则返回无穷远点
  980. }
  981. var w7 = w1.add(w2);
  982. var w8 = z1.multiply(z2).mod(q);
  983. var w9 = w3.square().mod(q);
  984. var w10 = w3.multiply(w9).mod(q);
  985. var w11 = w8.multiply(w6.square()).subtract(w7.multiply(w9)).mod(q);
  986. var x3 = w3.multiply(w11).mod(q);
  987. var y3 = w6.multiply(w9.multiply(w1).subtract(w11)).subtract(w4.multiply(w10)).mod(q);
  988. var z3 = w10.multiply(w8).mod(q);
  989. return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
  990. };
  991. /**
  992. * 自加
  993. *
  994. * 标准射影坐标系:
  995. *
  996. * λ1 = 3 * x1^2 + a * z1^2
  997. * λ2 = 2 * y1 * z1
  998. * λ3 = y1^2
  999. * λ4 = λ3 * x1 * z1
  1000. * λ5 = λ2^2
  1001. * λ6 = λ1^2 − 8 * λ4
  1002. * x3 = λ2 * λ6
  1003. * y3 = λ1 * (4 * λ4 − λ6) − 2 * λ5 * λ3
  1004. * z3 = λ2 * λ5
  1005. */
  1006. ECPointFp.prototype.twice = function twice() {
  1007. if (this.isInfinity()) return this;
  1008. if (!this.y.toBigInteger().signum()) return this.curve.infinity;
  1009. var x1 = this.x.toBigInteger();
  1010. var y1 = this.y.toBigInteger();
  1011. var z1 = this.z;
  1012. var q = this.curve.q;
  1013. var a = this.curve.a.toBigInteger();
  1014. var w1 = x1.square().multiply(THREE).add(a.multiply(z1.square())).mod(q);
  1015. var w2 = y1.shiftLeft(1).multiply(z1).mod(q);
  1016. var w3 = y1.square().mod(q);
  1017. var w4 = w3.multiply(x1).multiply(z1).mod(q);
  1018. var w5 = w2.square().mod(q);
  1019. var w6 = w1.square().subtract(w4.shiftLeft(3)).mod(q);
  1020. var x3 = w2.multiply(w6).mod(q);
  1021. var y3 = w1.multiply(w4.shiftLeft(2).subtract(w6)).subtract(w5.shiftLeft(1).multiply(w3)).mod(q);
  1022. var z3 = w2.multiply(w5).mod(q);
  1023. return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
  1024. };
  1025. /**
  1026. * 倍点计算
  1027. */
  1028. ECPointFp.prototype.multiply = function multiply(k) {
  1029. if (this.isInfinity()) return this;
  1030. if (!k.signum()) return this.curve.infinity;
  1031. // 使用加减法
  1032. var k3 = k.multiply(THREE);
  1033. var neg = this.negate();
  1034. var Q = this;
  1035. for (var i = k3.bitLength() - 2; i > 0; i--) {
  1036. Q = Q.twice();
  1037. var k3Bit = k3.testBit(i);
  1038. var kBit = k.testBit(i);
  1039. if (k3Bit !== kBit) {
  1040. Q = Q.add(k3Bit ? this : neg);
  1041. }
  1042. }
  1043. return Q;
  1044. };
  1045. return ECPointFp;
  1046. }();
  1047. /**
  1048. * 椭圆曲线 y^2 = x^3 + ax + b
  1049. */
  1050. var ECCurveFp = function () {
  1051. function ECCurveFp(q, a, b) {
  1052. _classCallCheck(this, ECCurveFp);
  1053. this.q = q;
  1054. this.a = this.fromBigInteger(a);
  1055. this.b = this.fromBigInteger(b);
  1056. this.infinity = new ECPointFp(this, null, null); // 无穷远点
  1057. }
  1058. /**
  1059. * 判断两个椭圆曲线是否相等
  1060. */
  1061. ECCurveFp.prototype.equals = function equals(other) {
  1062. if (other === this) return true;
  1063. return this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b);
  1064. };
  1065. /**
  1066. * 生成椭圆曲线域元素
  1067. */
  1068. ECCurveFp.prototype.fromBigInteger = function fromBigInteger(x) {
  1069. return new ECFieldElementFp(this.q, x);
  1070. };
  1071. /**
  1072. * 解析 16 进制串为椭圆曲线点
  1073. */
  1074. ECCurveFp.prototype.decodePointHex = function decodePointHex(s) {
  1075. switch (parseInt(s.substr(0, 2), 16)) {
  1076. // 第一个字节
  1077. case 0:
  1078. return this.infinity;
  1079. case 2:
  1080. case 3:
  1081. // 压缩
  1082. var x = this.fromBigInteger(new BigInteger(s.substr(2), 16));
  1083. // 对 p ≡ 3 (mod4),即存在正整数 u,使得 p = 4u + 3
  1084. // 计算 y = (√ (x^3 + ax + b) % p)^(u + 1) modp
  1085. 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));
  1086. // 算出结果 2 进制最后 1 位不等于第 1 个字节减 2 则取反
  1087. if (!y.toBigInteger().mod(TWO).equals(new BigInteger(s.substr(0, 2), 16).subtract(TWO))) {
  1088. y = y.negate();
  1089. }
  1090. return new ECPointFp(this, x, y);
  1091. case 4:
  1092. case 6:
  1093. case 7:
  1094. var len = (s.length - 2) / 2;
  1095. var xHex = s.substr(2, len);
  1096. var yHex = s.substr(len + 2, len);
  1097. return new ECPointFp(this, this.fromBigInteger(new BigInteger(xHex, 16)), this.fromBigInteger(new BigInteger(yHex, 16)));
  1098. default:
  1099. // 不支持
  1100. return null;
  1101. }
  1102. };
  1103. return ECCurveFp;
  1104. }();
  1105. module.exports = {
  1106. ECPointFp: ECPointFp,
  1107. ECCurveFp: ECCurveFp
  1108. };
  1109. /***/ }),
  1110. /* 7 */
  1111. /***/ (function(module, exports, __webpack_require__) {
  1112. "use strict";
  1113. var _require = __webpack_require__(1),
  1114. sm3 = _require.sm3,
  1115. hmac = _require.hmac;
  1116. /**
  1117. * 补全16进制字符串
  1118. */
  1119. function leftPad(input, num) {
  1120. if (input.length >= num) return input;
  1121. return new Array(num - input.length + 1).join('0') + input;
  1122. }
  1123. /**
  1124. * 字节数组转 16 进制串
  1125. */
  1126. function ArrayToHex(arr) {
  1127. return arr.map(function (item) {
  1128. item = item.toString(16);
  1129. return item.length === 1 ? '0' + item : item;
  1130. }).join('');
  1131. }
  1132. /**
  1133. * 转成字节数组
  1134. */
  1135. function hexToArray(hexStr) {
  1136. var words = [];
  1137. var hexStrLength = hexStr.length;
  1138. if (hexStrLength % 2 !== 0) {
  1139. hexStr = leftPad(hexStr, hexStrLength + 1);
  1140. }
  1141. hexStrLength = hexStr.length;
  1142. for (var i = 0; i < hexStrLength; i += 2) {
  1143. words.push(parseInt(hexStr.substr(i, 2), 16));
  1144. }
  1145. return words;
  1146. }
  1147. /**
  1148. * utf8 串转字节数组
  1149. */
  1150. function utf8ToArray(str) {
  1151. var arr = [];
  1152. for (var i = 0, len = str.length; i < len; i++) {
  1153. var point = str.codePointAt(i);
  1154. if (point <= 0x007f) {
  1155. // 单字节,标量值:00000000 00000000 0zzzzzzz
  1156. arr.push(point);
  1157. } else if (point <= 0x07ff) {
  1158. // 双字节,标量值:00000000 00000yyy yyzzzzzz
  1159. arr.push(0xc0 | point >>> 6); // 110yyyyy(0xc0-0xdf)
  1160. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1161. } else if (point <= 0xD7FF || point >= 0xE000 && point <= 0xFFFF) {
  1162. // 三字节:标量值:00000000 xxxxyyyy yyzzzzzz
  1163. arr.push(0xe0 | point >>> 12); // 1110xxxx(0xe0-0xef)
  1164. arr.push(0x80 | point >>> 6 & 0x3f); // 10yyyyyy(0x80-0xbf)
  1165. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1166. } else if (point >= 0x010000 && point <= 0x10FFFF) {
  1167. // 四字节:标量值:000wwwxx xxxxyyyy yyzzzzzz
  1168. i++;
  1169. arr.push(0xf0 | point >>> 18 & 0x1c); // 11110www(0xf0-0xf7)
  1170. arr.push(0x80 | point >>> 12 & 0x3f); // 10xxxxxx(0x80-0xbf)
  1171. arr.push(0x80 | point >>> 6 & 0x3f); // 10yyyyyy(0x80-0xbf)
  1172. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1173. } else {
  1174. // 五、六字节,暂时不支持
  1175. arr.push(point);
  1176. throw new Error('input is not supported');
  1177. }
  1178. }
  1179. return arr;
  1180. }
  1181. module.exports = function (input, options) {
  1182. input = typeof input === 'string' ? utf8ToArray(input) : Array.prototype.slice.call(input);
  1183. if (options) {
  1184. var mode = options.mode || 'hmac';
  1185. if (mode !== 'hmac') throw new Error('invalid mode');
  1186. var key = options.key;
  1187. if (!key) throw new Error('invalid key');
  1188. key = typeof key === 'string' ? hexToArray(key) : Array.prototype.slice.call(key);
  1189. return ArrayToHex(hmac(input, key));
  1190. }
  1191. return ArrayToHex(sm3(input));
  1192. };
  1193. /***/ }),
  1194. /* 8 */
  1195. /***/ (function(module, exports, __webpack_require__) {
  1196. "use strict";
  1197. /* eslint-disable no-bitwise, no-mixed-operators, complexity */
  1198. var DECRYPT = 0;
  1199. var ROUND = 32;
  1200. var BLOCK = 16;
  1201. 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];
  1202. 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];
  1203. /**
  1204. * 16 进制串转字节数组
  1205. */
  1206. function hexToArray(str) {
  1207. var arr = [];
  1208. for (var i = 0, len = str.length; i < len; i += 2) {
  1209. arr.push(parseInt(str.substr(i, 2), 16));
  1210. }
  1211. return arr;
  1212. }
  1213. /**
  1214. * 字节数组转 16 进制串
  1215. */
  1216. function ArrayToHex(arr) {
  1217. return arr.map(function (item) {
  1218. item = item.toString(16);
  1219. return item.length === 1 ? '0' + item : item;
  1220. }).join('');
  1221. }
  1222. /**
  1223. * utf8 串转字节数组
  1224. */
  1225. function utf8ToArray(str) {
  1226. var arr = [];
  1227. for (var i = 0, len = str.length; i < len; i++) {
  1228. var point = str.codePointAt(i);
  1229. if (point <= 0x007f) {
  1230. // 单字节,标量值:00000000 00000000 0zzzzzzz
  1231. arr.push(point);
  1232. } else if (point <= 0x07ff) {
  1233. // 双字节,标量值:00000000 00000yyy yyzzzzzz
  1234. arr.push(0xc0 | point >>> 6); // 110yyyyy(0xc0-0xdf)
  1235. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1236. } else if (point <= 0xD7FF || point >= 0xE000 && point <= 0xFFFF) {
  1237. // 三字节:标量值:00000000 xxxxyyyy yyzzzzzz
  1238. arr.push(0xe0 | point >>> 12); // 1110xxxx(0xe0-0xef)
  1239. arr.push(0x80 | point >>> 6 & 0x3f); // 10yyyyyy(0x80-0xbf)
  1240. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1241. } else if (point >= 0x010000 && point <= 0x10FFFF) {
  1242. // 四字节:标量值:000wwwxx xxxxyyyy yyzzzzzz
  1243. i++;
  1244. arr.push(0xf0 | point >>> 18 & 0x1c); // 11110www(0xf0-0xf7)
  1245. arr.push(0x80 | point >>> 12 & 0x3f); // 10xxxxxx(0x80-0xbf)
  1246. arr.push(0x80 | point >>> 6 & 0x3f); // 10yyyyyy(0x80-0xbf)
  1247. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1248. } else {
  1249. // 五、六字节,暂时不支持
  1250. arr.push(point);
  1251. throw new Error('input is not supported');
  1252. }
  1253. }
  1254. return arr;
  1255. }
  1256. /**
  1257. * 字节数组转 utf8 串
  1258. */
  1259. function arrayToUtf8(arr) {
  1260. var str = [];
  1261. for (var i = 0, len = arr.length; i < len; i++) {
  1262. if (arr[i] >= 0xf0 && arr[i] <= 0xf7) {
  1263. // 四字节
  1264. str.push(String.fromCodePoint(((arr[i] & 0x07) << 18) + ((arr[i + 1] & 0x3f) << 12) + ((arr[i + 2] & 0x3f) << 6) + (arr[i + 3] & 0x3f)));
  1265. i += 3;
  1266. } else if (arr[i] >= 0xe0 && arr[i] <= 0xef) {
  1267. // 三字节
  1268. str.push(String.fromCodePoint(((arr[i] & 0x0f) << 12) + ((arr[i + 1] & 0x3f) << 6) + (arr[i + 2] & 0x3f)));
  1269. i += 2;
  1270. } else if (arr[i] >= 0xc0 && arr[i] <= 0xdf) {
  1271. // 双字节
  1272. str.push(String.fromCodePoint(((arr[i] & 0x1f) << 6) + (arr[i + 1] & 0x3f)));
  1273. i++;
  1274. } else {
  1275. // 单字节
  1276. str.push(String.fromCodePoint(arr[i]));
  1277. }
  1278. }
  1279. return str.join('');
  1280. }
  1281. /**
  1282. * 32 比特循环左移
  1283. */
  1284. function rotl(x, y) {
  1285. return x << y | x >>> 32 - y;
  1286. }
  1287. /**
  1288. * 非线性变换
  1289. */
  1290. function byteSub(a) {
  1291. return (Sbox[a >>> 24 & 0xFF] & 0xFF) << 24 | (Sbox[a >>> 16 & 0xFF] & 0xFF) << 16 | (Sbox[a >>> 8 & 0xFF] & 0xFF) << 8 | Sbox[a & 0xFF] & 0xFF;
  1292. }
  1293. /**
  1294. * 线性变换,加密/解密用
  1295. */
  1296. function l1(b) {
  1297. return b ^ rotl(b, 2) ^ rotl(b, 10) ^ rotl(b, 18) ^ rotl(b, 24);
  1298. }
  1299. /**
  1300. * 线性变换,生成轮密钥用
  1301. */
  1302. function l2(b) {
  1303. return b ^ rotl(b, 13) ^ rotl(b, 23);
  1304. }
  1305. /**
  1306. * 以一组 128 比特进行加密/解密操作
  1307. */
  1308. function sms4Crypt(input, output, roundKey) {
  1309. var x = new Array(4);
  1310. // 字节数组转成字数组(此处 1 字 = 32 比特)
  1311. var tmp = new Array(4);
  1312. for (var i = 0; i < 4; i++) {
  1313. tmp[0] = input[4 * i] & 0xff;
  1314. tmp[1] = input[4 * i + 1] & 0xff;
  1315. tmp[2] = input[4 * i + 2] & 0xff;
  1316. tmp[3] = input[4 * i + 3] & 0xff;
  1317. x[i] = tmp[0] << 24 | tmp[1] << 16 | tmp[2] << 8 | tmp[3];
  1318. }
  1319. // x[i + 4] = x[i] ^ l1(byteSub(x[i + 1] ^ x[i + 2] ^ x[i + 3] ^ roundKey[i]))
  1320. for (var r = 0, mid; r < 32; r += 4) {
  1321. mid = x[1] ^ x[2] ^ x[3] ^ roundKey[r + 0];
  1322. x[0] ^= l1(byteSub(mid)); // x[4]
  1323. mid = x[2] ^ x[3] ^ x[0] ^ roundKey[r + 1];
  1324. x[1] ^= l1(byteSub(mid)); // x[5]
  1325. mid = x[3] ^ x[0] ^ x[1] ^ roundKey[r + 2];
  1326. x[2] ^= l1(byteSub(mid)); // x[6]
  1327. mid = x[0] ^ x[1] ^ x[2] ^ roundKey[r + 3];
  1328. x[3] ^= l1(byteSub(mid)); // x[7]
  1329. }
  1330. // 反序变换
  1331. for (var j = 0; j < 16; j += 4) {
  1332. output[j] = x[3 - j / 4] >>> 24 & 0xff;
  1333. output[j + 1] = x[3 - j / 4] >>> 16 & 0xff;
  1334. output[j + 2] = x[3 - j / 4] >>> 8 & 0xff;
  1335. output[j + 3] = x[3 - j / 4] & 0xff;
  1336. }
  1337. }
  1338. /**
  1339. * 密钥扩展算法
  1340. */
  1341. function sms4KeyExt(key, roundKey, cryptFlag) {
  1342. var x = new Array(4);
  1343. // 字节数组转成字数组(此处 1 字 = 32 比特)
  1344. var tmp = new Array(4);
  1345. for (var i = 0; i < 4; i++) {
  1346. tmp[0] = key[0 + 4 * i] & 0xff;
  1347. tmp[1] = key[1 + 4 * i] & 0xff;
  1348. tmp[2] = key[2 + 4 * i] & 0xff;
  1349. tmp[3] = key[3 + 4 * i] & 0xff;
  1350. x[i] = tmp[0] << 24 | tmp[1] << 16 | tmp[2] << 8 | tmp[3];
  1351. }
  1352. // 与系统参数做异或
  1353. x[0] ^= 0xa3b1bac6;
  1354. x[1] ^= 0x56aa3350;
  1355. x[2] ^= 0x677d9197;
  1356. x[3] ^= 0xb27022dc;
  1357. // roundKey[i] = x[i + 4] = x[i] ^ l2(byteSub(x[i + 1] ^ x[i + 2] ^ x[i + 3] ^ CK[i]))
  1358. for (var r = 0, mid; r < 32; r += 4) {
  1359. mid = x[1] ^ x[2] ^ x[3] ^ CK[r + 0];
  1360. roundKey[r + 0] = x[0] ^= l2(byteSub(mid)); // x[4]
  1361. mid = x[2] ^ x[3] ^ x[0] ^ CK[r + 1];
  1362. roundKey[r + 1] = x[1] ^= l2(byteSub(mid)); // x[5]
  1363. mid = x[3] ^ x[0] ^ x[1] ^ CK[r + 2];
  1364. roundKey[r + 2] = x[2] ^= l2(byteSub(mid)); // x[6]
  1365. mid = x[0] ^ x[1] ^ x[2] ^ CK[r + 3];
  1366. roundKey[r + 3] = x[3] ^= l2(byteSub(mid)); // x[7]
  1367. }
  1368. // 解密时使用反序的轮密钥
  1369. if (cryptFlag === DECRYPT) {
  1370. for (var _r = 0, _mid; _r < 16; _r++) {
  1371. _mid = roundKey[_r];
  1372. roundKey[_r] = roundKey[31 - _r];
  1373. roundKey[31 - _r] = _mid;
  1374. }
  1375. }
  1376. }
  1377. function sm4(inArray, key, cryptFlag) {
  1378. var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {},
  1379. _ref$padding = _ref.padding,
  1380. padding = _ref$padding === undefined ? 'pkcs#7' : _ref$padding,
  1381. mode = _ref.mode,
  1382. _ref$iv = _ref.iv,
  1383. iv = _ref$iv === undefined ? [] : _ref$iv,
  1384. _ref$output = _ref.output,
  1385. output = _ref$output === undefined ? 'string' : _ref$output;
  1386. if (mode === 'cbc') {
  1387. // CBC 模式,默认走 ECB 模式
  1388. if (typeof iv === 'string') iv = hexToArray(iv);
  1389. if (iv.length !== 128 / 8) {
  1390. // iv 不是 128 比特
  1391. throw new Error('iv is invalid');
  1392. }
  1393. }
  1394. // 检查 key
  1395. if (typeof key === 'string') key = hexToArray(key);
  1396. if (key.length !== 128 / 8) {
  1397. // key 不是 128 比特
  1398. throw new Error('key is invalid');
  1399. }
  1400. // 检查输入
  1401. if (typeof inArray === 'string') {
  1402. if (cryptFlag !== DECRYPT) {
  1403. // 加密,输入为 utf8 串
  1404. inArray = utf8ToArray(inArray);
  1405. } else {
  1406. // 解密,输入为 16 进制串
  1407. inArray = hexToArray(inArray);
  1408. }
  1409. } else {
  1410. inArray = [].concat(inArray);
  1411. }
  1412. // 新增填充,sm4 是 16 个字节一个分组,所以统一走到 pkcs#7
  1413. if ((padding === 'pkcs#5' || padding === 'pkcs#7') && cryptFlag !== DECRYPT) {
  1414. var paddingCount = BLOCK - inArray.length % BLOCK;
  1415. for (var i = 0; i < paddingCount; i++) {
  1416. inArray.push(paddingCount);
  1417. }
  1418. }
  1419. // 生成轮密钥
  1420. var roundKey = new Array(ROUND);
  1421. sms4KeyExt(key, roundKey, cryptFlag);
  1422. var outArray = [];
  1423. var lastVector = iv;
  1424. var restLen = inArray.length;
  1425. var point = 0;
  1426. while (restLen >= BLOCK) {
  1427. var input = inArray.slice(point, point + 16);
  1428. var _output = new Array(16);
  1429. if (mode === 'cbc') {
  1430. for (var _i = 0; _i < BLOCK; _i++) {
  1431. if (cryptFlag !== DECRYPT) {
  1432. // 加密过程在组加密前进行异或
  1433. input[_i] ^= lastVector[_i];
  1434. }
  1435. }
  1436. }
  1437. sms4Crypt(input, _output, roundKey);
  1438. for (var _i2 = 0; _i2 < BLOCK; _i2++) {
  1439. if (mode === 'cbc') {
  1440. if (cryptFlag === DECRYPT) {
  1441. // 解密过程在组解密后进行异或
  1442. _output[_i2] ^= lastVector[_i2];
  1443. }
  1444. }
  1445. outArray[point + _i2] = _output[_i2];
  1446. }
  1447. if (mode === 'cbc') {
  1448. if (cryptFlag !== DECRYPT) {
  1449. // 使用上一次输出作为加密向量
  1450. lastVector = _output;
  1451. } else {
  1452. // 使用上一次输入作为解密向量
  1453. lastVector = input;
  1454. }
  1455. }
  1456. restLen -= BLOCK;
  1457. point += BLOCK;
  1458. }
  1459. // 去除填充,sm4 是 16 个字节一个分组,所以统一走到 pkcs#7
  1460. if ((padding === 'pkcs#5' || padding === 'pkcs#7') && cryptFlag === DECRYPT) {
  1461. var len = outArray.length;
  1462. var _paddingCount = outArray[len - 1];
  1463. for (var _i3 = 1; _i3 <= _paddingCount; _i3++) {
  1464. if (outArray[len - _i3] !== _paddingCount) throw new Error('padding is invalid');
  1465. }
  1466. outArray.splice(len - _paddingCount, _paddingCount);
  1467. }
  1468. // 调整输出
  1469. if (output !== 'array') {
  1470. if (cryptFlag !== DECRYPT) {
  1471. // 加密,输出转 16 进制串
  1472. return ArrayToHex(outArray);
  1473. } else {
  1474. // 解密,输出转 utf8 串
  1475. return arrayToUtf8(outArray);
  1476. }
  1477. } else {
  1478. return outArray;
  1479. }
  1480. }
  1481. module.exports = {
  1482. encrypt: function encrypt(inArray, key, options) {
  1483. return sm4(inArray, key, 1, options);
  1484. },
  1485. decrypt: function decrypt(inArray, key, options) {
  1486. return sm4(inArray, key, 0, options);
  1487. }
  1488. };
  1489. /***/ })
  1490. /******/ ]);