index.js 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742
  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. * 循环左移
  98. */
  99. function rotl(x, n) {
  100. var result = [];
  101. var a = ~~(n / 8); // 偏移 a 字节
  102. var b = n % 8; // 偏移 b 位
  103. for (var i = 0, len = x.length; i < len; i++) {
  104. // current << b + (current + 1) >>> (8 - b)
  105. result[i] = (x[(i + a) % len] << b & 0xff) + (x[(i + a + 1) % len] >>> 8 - b & 0xff);
  106. }
  107. return result;
  108. }
  109. /**
  110. * 二进制异或运算
  111. */
  112. function xor(x, y) {
  113. var result = [];
  114. for (var i = x.length - 1; i >= 0; i--) {
  115. result[i] = (x[i] ^ y[i]) & 0xff;
  116. }return result;
  117. }
  118. /**
  119. * 二进制与运算
  120. */
  121. function and(x, y) {
  122. var result = [];
  123. for (var i = x.length - 1; i >= 0; i--) {
  124. result[i] = x[i] & y[i] & 0xff;
  125. }return result;
  126. }
  127. /**
  128. * 二进制或运算
  129. */
  130. function or(x, y) {
  131. var result = [];
  132. for (var i = x.length - 1; i >= 0; i--) {
  133. result[i] = (x[i] | y[i]) & 0xff;
  134. }return result;
  135. }
  136. /**
  137. * 二进制与运算
  138. */
  139. function add(x, y) {
  140. var result = [];
  141. var temp = 0;
  142. for (var i = x.length - 1; i >= 0; i--) {
  143. var sum = x[i] + y[i] + temp;
  144. if (sum > 0xff) {
  145. temp = 1;
  146. result[i] = sum & 0xff;
  147. } else {
  148. temp = 0;
  149. result[i] = sum & 0xff;
  150. }
  151. }
  152. return result;
  153. }
  154. /**
  155. * 二进制非运算
  156. */
  157. function not(x) {
  158. var result = [];
  159. for (var i = x.length - 1; i >= 0; i--) {
  160. result[i] = ~x[i] & 0xff;
  161. }return result;
  162. }
  163. /**
  164. * 压缩函数中的置换函数 P1(X) = X xor (X <<< 9) xor (X <<< 17)
  165. */
  166. function P0(X) {
  167. return xor(xor(X, rotl(X, 9)), rotl(X, 17));
  168. }
  169. /**
  170. * 消息扩展中的置换函数 P1(X) = X xor (X <<< 15) xor (X <<< 23)
  171. */
  172. function P1(X) {
  173. return xor(xor(X, rotl(X, 15)), rotl(X, 23));
  174. }
  175. /**
  176. * 布尔函数 FF
  177. */
  178. function FF(X, Y, Z, j) {
  179. return j >= 0 && j <= 15 ? xor(xor(X, Y), Z) : or(or(and(X, Y), and(X, Z)), and(Y, Z));
  180. }
  181. /**
  182. * 布尔函数 GG
  183. */
  184. function GG(X, Y, Z, j) {
  185. return j >= 0 && j <= 15 ? xor(xor(X, Y), Z) : or(and(X, Y), and(not(X), Z));
  186. }
  187. /**
  188. * 压缩函数
  189. */
  190. function CF(V, Bi) {
  191. // 消息扩展
  192. var W = [];
  193. var M = []; // W'
  194. // 将消息分组B划分为 16 个字 W0, W1,……,W15
  195. for (var i = 0; i < 16; i++) {
  196. var start = i * 4;
  197. W.push(Bi.slice(start, start + 4));
  198. }
  199. // 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]
  200. for (var j = 16; j < 68; j++) {
  201. W.push(xor(xor(P1(xor(xor(W[j - 16], W[j - 9]), rotl(W[j - 3], 15))), rotl(W[j - 13], 7)), W[j - 6]));
  202. }
  203. // W′0 ~ W′63:W′[j] = W[j] xor W[j+4]
  204. for (var _j = 0; _j < 64; _j++) {
  205. M.push(xor(W[_j], W[_j + 4]));
  206. }
  207. // 压缩
  208. var T1 = [0x79, 0xcc, 0x45, 0x19];
  209. var T2 = [0x7a, 0x87, 0x9d, 0x8a];
  210. // 字寄存器
  211. var A = V.slice(0, 4);
  212. var B = V.slice(4, 8);
  213. var C = V.slice(8, 12);
  214. var D = V.slice(12, 16);
  215. var E = V.slice(16, 20);
  216. var F = V.slice(20, 24);
  217. var G = V.slice(24, 28);
  218. var H = V.slice(28, 32);
  219. // 中间变量
  220. var SS1 = void 0;
  221. var SS2 = void 0;
  222. var TT1 = void 0;
  223. var TT2 = void 0;
  224. for (var _j2 = 0; _j2 < 64; _j2++) {
  225. var T = _j2 >= 0 && _j2 <= 15 ? T1 : T2;
  226. SS1 = rotl(add(add(rotl(A, 12), E), rotl(T, _j2)), 7);
  227. SS2 = xor(SS1, rotl(A, 12));
  228. TT1 = add(add(add(FF(A, B, C, _j2), D), SS2), M[_j2]);
  229. TT2 = add(add(add(GG(E, F, G, _j2), H), SS1), W[_j2]);
  230. D = C;
  231. C = rotl(B, 9);
  232. B = A;
  233. A = TT1;
  234. H = G;
  235. G = rotl(F, 19);
  236. F = E;
  237. E = P0(TT2);
  238. }
  239. return xor([].concat(A, B, C, D, E, F, G, H), V);
  240. }
  241. module.exports = function (array) {
  242. // 填充
  243. var len = array.length * 8;
  244. // k 是满足 len + 1 + k = 448mod512 的最小的非负整数
  245. var k = len % 512;
  246. // 如果 448 <= (512 % len) < 512,需要多补充 (len % 448) 比特'0'以满足总比特长度为512的倍数
  247. k = k >= 448 ? 512 - k % 448 - 1 : 448 - k - 1;
  248. // 填充
  249. var kArr = new Array((k - 7) / 8);
  250. for (var i = 0, _len = kArr.length; i < _len; i++) {
  251. kArr[i] = 0;
  252. }var lenArr = [];
  253. len = len.toString(2);
  254. for (var _i = 7; _i >= 0; _i--) {
  255. if (len.length > 8) {
  256. var start = len.length - 8;
  257. lenArr[_i] = parseInt(len.substr(start), 2);
  258. len = len.substr(0, start);
  259. } else if (len.length > 0) {
  260. lenArr[_i] = parseInt(len, 2);
  261. len = '';
  262. } else {
  263. lenArr[_i] = 0;
  264. }
  265. }
  266. var m = [].concat(array, [0x80], kArr, lenArr);
  267. // 迭代压缩
  268. var n = m.length / 64;
  269. var V = [0x73, 0x80, 0x16, 0x6f, 0x49, 0x14, 0xb2, 0xb9, 0x17, 0x24, 0x42, 0xd7, 0xda, 0x8a, 0x06, 0x00, 0xa9, 0x6f, 0x30, 0xbc, 0x16, 0x31, 0x38, 0xaa, 0xe3, 0x8d, 0xee, 0x4d, 0xb0, 0xfb, 0x0e, 0x4e];
  270. for (var _i2 = 0; _i2 < n; _i2++) {
  271. var _start = 64 * _i2;
  272. var B = m.slice(_start, _start + 64);
  273. V = CF(V, B);
  274. }
  275. return V;
  276. };
  277. /***/ }),
  278. /* 2 */
  279. /***/ (function(module, exports, __webpack_require__) {
  280. "use strict";
  281. module.exports = {
  282. sm2: __webpack_require__(3),
  283. sm3: __webpack_require__(7),
  284. sm4: __webpack_require__(8)
  285. };
  286. /***/ }),
  287. /* 3 */
  288. /***/ (function(module, exports, __webpack_require__) {
  289. "use strict";
  290. /* eslint-disable no-use-before-define */
  291. var _require = __webpack_require__(0),
  292. BigInteger = _require.BigInteger;
  293. var _require2 = __webpack_require__(4),
  294. encodeDer = _require2.encodeDer,
  295. decodeDer = _require2.decodeDer;
  296. var _ = __webpack_require__(5);
  297. var sm3 = __webpack_require__(1);
  298. var _$generateEcparam = _.generateEcparam(),
  299. G = _$generateEcparam.G,
  300. curve = _$generateEcparam.curve,
  301. n = _$generateEcparam.n;
  302. var C1C2C3 = 0;
  303. /**
  304. * 加密
  305. */
  306. function doEncrypt(msg, publicKey) {
  307. var cipherMode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  308. msg = _.hexToArray(_.utf8ToHex(msg));
  309. publicKey = _.getGlobalCurve().decodePointHex(publicKey); // 先将公钥转成点
  310. var keypair = _.generateKeyPairHex();
  311. var k = new BigInteger(keypair.privateKey, 16); // 随机数 k
  312. // c1 = k * G
  313. var c1 = keypair.publicKey;
  314. if (c1.length > 128) c1 = c1.substr(c1.length - 128);
  315. // (x2, y2) = k * publicKey
  316. var p = publicKey.multiply(k);
  317. var x2 = _.hexToArray(_.leftPad(p.getX().toBigInteger().toRadix(16), 64));
  318. var y2 = _.hexToArray(_.leftPad(p.getY().toBigInteger().toRadix(16), 64));
  319. // c3 = hash(x2 || msg || y2)
  320. var c3 = _.arrayToHex(sm3([].concat(x2, msg, y2)));
  321. var ct = 1;
  322. var offset = 0;
  323. var t = []; // 256 位
  324. var z = [].concat(x2, y2);
  325. var nextT = function nextT() {
  326. // (1) Hai = hash(z || ct)
  327. // (2) ct++
  328. t = sm3([].concat(z, [ct >> 24 & 0x00ff, ct >> 16 & 0x00ff, ct >> 8 & 0x00ff, ct & 0x00ff]));
  329. ct++;
  330. offset = 0;
  331. };
  332. nextT(); // 先生成 Ha1
  333. for (var i = 0, len = msg.length; i < len; i++) {
  334. // t = Ha1 || Ha2 || Ha3 || Ha4
  335. if (offset === t.length) nextT();
  336. // c2 = msg ^ t
  337. msg[i] ^= t[offset++] & 0xff;
  338. }
  339. var c2 = _.arrayToHex(msg);
  340. return cipherMode === C1C2C3 ? c1 + c2 + c3 : c1 + c3 + c2;
  341. }
  342. /**
  343. * 解密
  344. */
  345. function doDecrypt(encryptData, privateKey) {
  346. var cipherMode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  347. privateKey = new BigInteger(privateKey, 16);
  348. var c3 = encryptData.substr(128, 64);
  349. var c2 = encryptData.substr(128 + 64);
  350. if (cipherMode === C1C2C3) {
  351. c3 = encryptData.substr(encryptData.length - 64);
  352. c2 = encryptData.substr(128, encryptData.length - 128 - 64);
  353. }
  354. var msg = _.hexToArray(c2);
  355. var c1 = _.getGlobalCurve().decodePointHex('04' + encryptData.substr(0, 128));
  356. var p = c1.multiply(privateKey);
  357. var x2 = _.hexToArray(_.leftPad(p.getX().toBigInteger().toRadix(16), 64));
  358. var y2 = _.hexToArray(_.leftPad(p.getY().toBigInteger().toRadix(16), 64));
  359. var ct = 1;
  360. var offset = 0;
  361. var t = []; // 256 位
  362. var z = [].concat(x2, y2);
  363. var nextT = function nextT() {
  364. // (1) Hai = hash(z || ct)
  365. // (2) ct++
  366. t = sm3([].concat(z, [ct >> 24 & 0x00ff, ct >> 16 & 0x00ff, ct >> 8 & 0x00ff, ct & 0x00ff]));
  367. ct++;
  368. offset = 0;
  369. };
  370. nextT(); // 先生成 Ha1
  371. for (var i = 0, len = msg.length; i < len; i++) {
  372. // t = Ha1 || Ha2 || Ha3 || Ha4
  373. if (offset === t.length) nextT();
  374. // c2 = msg ^ t
  375. msg[i] ^= t[offset++] & 0xff;
  376. }
  377. // c3 = hash(x2 || msg || y2)
  378. var checkC3 = _.arrayToHex(sm3([].concat(x2, msg, y2)));
  379. return checkC3 === c3 ? _.arrayToUtf8(msg) : '';
  380. }
  381. /**
  382. * 签名
  383. */
  384. function doSignature(msg, privateKey) {
  385. var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
  386. pointPool = _ref.pointPool,
  387. der = _ref.der,
  388. hash = _ref.hash,
  389. publicKey = _ref.publicKey,
  390. userId = _ref.userId;
  391. var hashHex = typeof msg === 'string' ? _.utf8ToHex(msg) : _.arrayToHex(msg);
  392. if (hash) {
  393. // sm3杂凑
  394. publicKey = publicKey || getPublicKeyFromPrivateKey(privateKey);
  395. hashHex = getHash(hashHex, publicKey, userId);
  396. }
  397. var dA = new BigInteger(privateKey, 16);
  398. var e = new BigInteger(hashHex, 16);
  399. // k
  400. var k = null;
  401. var r = null;
  402. var s = null;
  403. do {
  404. do {
  405. var point = void 0;
  406. if (pointPool && pointPool.length) {
  407. point = pointPool.pop();
  408. } else {
  409. point = getPoint();
  410. }
  411. k = point.k;
  412. // r = (e + x1) mod n
  413. r = e.add(point.x1).mod(n);
  414. } while (r.equals(BigInteger.ZERO) || r.add(k).equals(n));
  415. // s = ((1 + dA)^-1 * (k - r * dA)) mod n
  416. s = dA.add(BigInteger.ONE).modInverse(n).multiply(k.subtract(r.multiply(dA))).mod(n);
  417. } while (s.equals(BigInteger.ZERO));
  418. if (der) return encodeDer(r, s); // asn.1 der 编码
  419. return _.leftPad(r.toString(16), 64) + _.leftPad(s.toString(16), 64);
  420. }
  421. /**
  422. * 验签
  423. */
  424. function doVerifySignature(msg, signHex, publicKey) {
  425. var _ref2 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {},
  426. der = _ref2.der,
  427. hash = _ref2.hash,
  428. userId = _ref2.userId;
  429. var hashHex = typeof msg === 'string' ? _.utf8ToHex(msg) : _.arrayToHex(msg);
  430. if (hash) {
  431. // sm3杂凑
  432. hashHex = getHash(hashHex, publicKey, userId);
  433. }
  434. var r = void 0;var s = void 0;
  435. if (der) {
  436. var decodeDerObj = decodeDer(signHex); // asn.1 der 解码
  437. r = decodeDerObj.r;
  438. s = decodeDerObj.s;
  439. } else {
  440. r = new BigInteger(signHex.substring(0, 64), 16);
  441. s = new BigInteger(signHex.substring(64), 16);
  442. }
  443. var PA = curve.decodePointHex(publicKey);
  444. var e = new BigInteger(hashHex, 16);
  445. // t = (r + s) mod n
  446. var t = r.add(s).mod(n);
  447. if (t.equals(BigInteger.ZERO)) return false;
  448. // x1y1 = s * G + t * PA
  449. var x1y1 = G.multiply(s).add(PA.multiply(t));
  450. // R = (e + x1) mod n
  451. var R = e.add(x1y1.getX().toBigInteger()).mod(n);
  452. return r.equals(R);
  453. }
  454. /**
  455. * sm3杂凑算法
  456. */
  457. function getHash(hashHex, publicKey) {
  458. var userId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '1234567812345678';
  459. // z = hash(entl || userId || a || b || gx || gy || px || py)
  460. userId = _.utf8ToHex(userId);
  461. var a = _.leftPad(G.curve.a.toBigInteger().toRadix(16), 64);
  462. var b = _.leftPad(G.curve.b.toBigInteger().toRadix(16), 64);
  463. var gx = _.leftPad(G.getX().toBigInteger().toRadix(16), 64);
  464. var gy = _.leftPad(G.getY().toBigInteger().toRadix(16), 64);
  465. if (publicKey.length > 128) publicKey = publicKey.substr(2, 128); // 干掉 '04'
  466. var px = publicKey.substr(0, 64);
  467. var py = publicKey.substr(64, 64);
  468. var data = _.hexToArray(userId + a + b + gx + gy + px + py);
  469. var entl = userId.length * 4;
  470. data.unshift(entl & 0x00ff);
  471. data.unshift(entl & 0xff00);
  472. var z = sm3(data);
  473. // e = hash(z || msg)
  474. return _.arrayToHex(sm3(z.concat(_.hexToArray(hashHex))));
  475. }
  476. /**
  477. * 计算公钥
  478. */
  479. function getPublicKeyFromPrivateKey(privateKey) {
  480. var PA = G.multiply(new BigInteger(privateKey, 16));
  481. var x = _.leftPad(PA.getX().toBigInteger().toString(16), 64);
  482. var y = _.leftPad(PA.getY().toBigInteger().toString(16), 64);
  483. return '04' + x + y;
  484. }
  485. /**
  486. * 获取椭圆曲线点
  487. */
  488. function getPoint() {
  489. var keypair = _.generateKeyPairHex();
  490. var PA = curve.decodePointHex(keypair.publicKey);
  491. keypair.k = new BigInteger(keypair.privateKey, 16);
  492. keypair.x1 = PA.getX().toBigInteger();
  493. return keypair;
  494. }
  495. module.exports = {
  496. generateKeyPairHex: _.generateKeyPairHex,
  497. doEncrypt: doEncrypt,
  498. doDecrypt: doDecrypt,
  499. doSignature: doSignature,
  500. doVerifySignature: doVerifySignature,
  501. getPoint: getPoint
  502. };
  503. /***/ }),
  504. /* 4 */
  505. /***/ (function(module, exports, __webpack_require__) {
  506. "use strict";
  507. 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; }
  508. 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; }
  509. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  510. /* eslint-disable class-methods-use-this */
  511. var _require = __webpack_require__(0),
  512. BigInteger = _require.BigInteger;
  513. function bigintToValue(bigint) {
  514. var h = bigint.toString(16);
  515. if (h[0] !== '-') {
  516. // 正数
  517. if (h.length % 2 === 1) h = '0' + h; // 补齐到整字节
  518. else if (!h.match(/^[0-7]/)) h = '00' + h; // 非0开头,则补一个全0字节
  519. } else {
  520. // 负数
  521. h = h.substr(1);
  522. var len = h.length;
  523. if (len % 2 === 1) len += 1; // 补齐到整字节
  524. else if (!h.match(/^[0-7]/)) len += 2; // 非0开头,则补一个全0字节
  525. var mask = '';
  526. for (var i = 0; i < len; i++) {
  527. mask += 'f';
  528. }mask = new BigInteger(mask, 16);
  529. // 对绝对值取反,加1
  530. h = mask.xor(bigint).add(BigInteger.ONE);
  531. h = h.toString(16).replace(/^-/, '');
  532. }
  533. return h;
  534. }
  535. var ASN1Object = function () {
  536. function ASN1Object() {
  537. _classCallCheck(this, ASN1Object);
  538. this.tlv = null;
  539. this.t = '00';
  540. this.l = '00';
  541. this.v = '';
  542. }
  543. /**
  544. * 获取 der 编码比特流16进制串
  545. */
  546. ASN1Object.prototype.getEncodedHex = function getEncodedHex() {
  547. if (!this.tlv) {
  548. this.v = this.getValue();
  549. this.l = this.getLength();
  550. this.tlv = this.t + this.l + this.v;
  551. }
  552. return this.tlv;
  553. };
  554. ASN1Object.prototype.getLength = function getLength() {
  555. var n = this.v.length / 2; // 字节数
  556. var nHex = n.toString(16);
  557. if (nHex.length % 2 === 1) nHex = '0' + nHex; // 补齐到整字节
  558. if (n < 128) {
  559. // 短格式,以 0 开头
  560. return nHex;
  561. } else {
  562. // 长格式,以 1 开头
  563. var head = 128 + nHex.length / 2; // 1(1位) + 真正的长度占用字节数(7位) + 真正的长度
  564. return head.toString(16) + nHex;
  565. }
  566. };
  567. ASN1Object.prototype.getValue = function getValue() {
  568. return '';
  569. };
  570. return ASN1Object;
  571. }();
  572. var DERInteger = function (_ASN1Object) {
  573. _inherits(DERInteger, _ASN1Object);
  574. function DERInteger(bigint) {
  575. _classCallCheck(this, DERInteger);
  576. var _this = _possibleConstructorReturn(this, _ASN1Object.call(this));
  577. _this.t = '02'; // 整型标签说明
  578. if (bigint) _this.v = bigintToValue(bigint);
  579. return _this;
  580. }
  581. DERInteger.prototype.getValue = function getValue() {
  582. return this.v;
  583. };
  584. return DERInteger;
  585. }(ASN1Object);
  586. var DERSequence = function (_ASN1Object2) {
  587. _inherits(DERSequence, _ASN1Object2);
  588. function DERSequence(asn1Array) {
  589. _classCallCheck(this, DERSequence);
  590. var _this2 = _possibleConstructorReturn(this, _ASN1Object2.call(this));
  591. _this2.t = '30'; // 序列标签说明
  592. _this2.asn1Array = asn1Array;
  593. return _this2;
  594. }
  595. DERSequence.prototype.getValue = function getValue() {
  596. this.v = this.asn1Array.map(function (asn1Object) {
  597. return asn1Object.getEncodedHex();
  598. }).join('');
  599. return this.v;
  600. };
  601. return DERSequence;
  602. }(ASN1Object);
  603. /**
  604. * 获取 l 占用字节数
  605. */
  606. function getLenOfL(str, start) {
  607. if (+str[start + 2] < 8) return 1; // l 以0开头,则表示短格式,只占一个字节
  608. return +str.substr(start + 2, 2) & 0x7f + 1; // 长格式,取第一个字节后7位作为长度真正占用字节数,再加上本身
  609. }
  610. /**
  611. * 获取 l
  612. */
  613. function getL(str, start) {
  614. // 获取 l
  615. var len = getLenOfL(str, start);
  616. var l = str.substr(start + 2, len * 2);
  617. if (!l) return -1;
  618. var bigint = +l[0] < 8 ? new BigInteger(l, 16) : new BigInteger(l.substr(2), 16);
  619. return bigint.intValue();
  620. }
  621. /**
  622. * 获取 v 的位置
  623. */
  624. function getStartOfV(str, start) {
  625. var len = getLenOfL(str, start);
  626. return start + (len + 1) * 2;
  627. }
  628. module.exports = {
  629. /**
  630. * ASN.1 der 编码,针对 sm2 签名
  631. */
  632. encodeDer: function encodeDer(r, s) {
  633. var derR = new DERInteger(r);
  634. var derS = new DERInteger(s);
  635. var derSeq = new DERSequence([derR, derS]);
  636. return derSeq.getEncodedHex();
  637. },
  638. /**
  639. * 解析 ASN.1 der,针对 sm2 验签
  640. */
  641. decodeDer: function decodeDer(input) {
  642. // 结构:
  643. // input = | tSeq | lSeq | vSeq |
  644. // vSeq = | tR | lR | vR | tS | lS | vS |
  645. var start = getStartOfV(input, 0);
  646. var vIndexR = getStartOfV(input, start);
  647. var lR = getL(input, start);
  648. var vR = input.substr(vIndexR, lR * 2);
  649. var nextStart = vIndexR + vR.length;
  650. var vIndexS = getStartOfV(input, nextStart);
  651. var lS = getL(input, nextStart);
  652. var vS = input.substr(vIndexS, lS * 2);
  653. var r = new BigInteger(vR, 16);
  654. var s = new BigInteger(vS, 16);
  655. return { r: r, s: s };
  656. }
  657. };
  658. /***/ }),
  659. /* 5 */
  660. /***/ (function(module, exports, __webpack_require__) {
  661. "use strict";
  662. /* eslint-disable no-bitwise, no-mixed-operators, no-use-before-define, max-len */
  663. var _require = __webpack_require__(0),
  664. BigInteger = _require.BigInteger,
  665. SecureRandom = _require.SecureRandom;
  666. var _require2 = __webpack_require__(6),
  667. ECCurveFp = _require2.ECCurveFp;
  668. var rng = new SecureRandom();
  669. var _generateEcparam = generateEcparam(),
  670. curve = _generateEcparam.curve,
  671. G = _generateEcparam.G,
  672. n = _generateEcparam.n;
  673. /**
  674. * 获取公共椭圆曲线
  675. */
  676. function getGlobalCurve() {
  677. return curve;
  678. }
  679. /**
  680. * 生成ecparam
  681. */
  682. function generateEcparam() {
  683. // 椭圆曲线
  684. var p = new BigInteger('FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF', 16);
  685. var a = new BigInteger('FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC', 16);
  686. var b = new BigInteger('28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93', 16);
  687. var curve = new ECCurveFp(p, a, b);
  688. // 基点
  689. var gxHex = '32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7';
  690. var gyHex = 'BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0';
  691. var G = curve.decodePointHex('04' + gxHex + gyHex);
  692. var n = new BigInteger('FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123', 16);
  693. return { curve: curve, G: G, n: n };
  694. }
  695. /**
  696. * 生成密钥对:publicKey = privateKey * G
  697. */
  698. function generateKeyPairHex() {
  699. var d = new BigInteger(n.bitLength(), rng).mod(n.subtract(BigInteger.ONE)).add(BigInteger.ONE); // 随机数
  700. var privateKey = leftPad(d.toString(16), 64);
  701. var P = G.multiply(d); // P = dG,p 为公钥,d 为私钥
  702. var Px = leftPad(P.getX().toBigInteger().toString(16), 64);
  703. var Py = leftPad(P.getY().toBigInteger().toString(16), 64);
  704. var publicKey = '04' + Px + Py;
  705. return { privateKey: privateKey, publicKey: publicKey };
  706. }
  707. /**
  708. * utf8串转16进制串
  709. */
  710. function utf8ToHex(input) {
  711. input = unescape(encodeURIComponent(input));
  712. var length = input.length;
  713. // 转换到字数组
  714. var words = [];
  715. for (var i = 0; i < length; i++) {
  716. words[i >>> 2] |= (input.charCodeAt(i) & 0xff) << 24 - i % 4 * 8;
  717. }
  718. // 转换到16进制
  719. var hexChars = [];
  720. for (var _i = 0; _i < length; _i++) {
  721. var bite = words[_i >>> 2] >>> 24 - _i % 4 * 8 & 0xff;
  722. hexChars.push((bite >>> 4).toString(16));
  723. hexChars.push((bite & 0x0f).toString(16));
  724. }
  725. return hexChars.join('');
  726. }
  727. /**
  728. * 补全16进制字符串
  729. */
  730. function leftPad(input, num) {
  731. if (input.length >= num) return input;
  732. return new Array(num - input.length + 1).join('0') + input;
  733. }
  734. /**
  735. * 转成16进制串
  736. */
  737. function arrayToHex(arr) {
  738. return arr.map(function (item) {
  739. item = item.toString(16);
  740. return item.length === 1 ? '0' + item : item;
  741. }).join('');
  742. }
  743. /**
  744. * 转成utf8串
  745. */
  746. function arrayToUtf8(arr) {
  747. var words = [];
  748. var j = 0;
  749. for (var i = 0; i < arr.length * 2; i += 2) {
  750. words[i >>> 3] |= parseInt(arr[j], 10) << 24 - i % 8 * 4;
  751. j++;
  752. }
  753. try {
  754. var latin1Chars = [];
  755. for (var _i2 = 0; _i2 < arr.length; _i2++) {
  756. var bite = words[_i2 >>> 2] >>> 24 - _i2 % 4 * 8 & 0xff;
  757. latin1Chars.push(String.fromCharCode(bite));
  758. }
  759. return decodeURIComponent(escape(latin1Chars.join('')));
  760. } catch (e) {
  761. throw new Error('Malformed UTF-8 data');
  762. }
  763. }
  764. /**
  765. * 转成字节数组
  766. */
  767. function hexToArray(hexStr) {
  768. var words = [];
  769. var hexStrLength = hexStr.length;
  770. if (hexStrLength % 2 !== 0) {
  771. hexStr = leftPad(hexStr, hexStrLength + 1);
  772. }
  773. hexStrLength = hexStr.length;
  774. for (var i = 0; i < hexStrLength; i += 2) {
  775. words.push(parseInt(hexStr.substr(i, 2), 16));
  776. }
  777. return words;
  778. }
  779. module.exports = {
  780. getGlobalCurve: getGlobalCurve,
  781. generateEcparam: generateEcparam,
  782. generateKeyPairHex: generateKeyPairHex,
  783. utf8ToHex: utf8ToHex,
  784. leftPad: leftPad,
  785. arrayToHex: arrayToHex,
  786. arrayToUtf8: arrayToUtf8,
  787. hexToArray: hexToArray
  788. };
  789. /***/ }),
  790. /* 6 */
  791. /***/ (function(module, exports, __webpack_require__) {
  792. "use strict";
  793. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  794. /* eslint-disable no-case-declarations, max-len */
  795. var _require = __webpack_require__(0),
  796. BigInteger = _require.BigInteger;
  797. /**
  798. * thanks for Tom Wu : http://www-cs-students.stanford.edu/~tjw/jsbn/
  799. *
  800. * Basic Javascript Elliptic Curve implementation
  801. * Ported loosely from BouncyCastle's Java EC code
  802. * Only Fp curves implemented for now
  803. */
  804. var THREE = new BigInteger('3');
  805. /**
  806. * 椭圆曲线域元素
  807. */
  808. var ECFieldElementFp = function () {
  809. function ECFieldElementFp(q, x) {
  810. _classCallCheck(this, ECFieldElementFp);
  811. this.x = x;
  812. this.q = q;
  813. // TODO if (x.compareTo(q) >= 0) error
  814. }
  815. /**
  816. * 判断相等
  817. */
  818. ECFieldElementFp.prototype.equals = function equals(other) {
  819. if (other === this) return true;
  820. return this.q.equals(other.q) && this.x.equals(other.x);
  821. };
  822. /**
  823. * 返回具体数值
  824. */
  825. ECFieldElementFp.prototype.toBigInteger = function toBigInteger() {
  826. return this.x;
  827. };
  828. /**
  829. * 取反
  830. */
  831. ECFieldElementFp.prototype.negate = function negate() {
  832. return new ECFieldElementFp(this.q, this.x.negate().mod(this.q));
  833. };
  834. /**
  835. * 相加
  836. */
  837. ECFieldElementFp.prototype.add = function add(b) {
  838. return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q));
  839. };
  840. /**
  841. * 相减
  842. */
  843. ECFieldElementFp.prototype.subtract = function subtract(b) {
  844. return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q));
  845. };
  846. /**
  847. * 相乘
  848. */
  849. ECFieldElementFp.prototype.multiply = function multiply(b) {
  850. return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q));
  851. };
  852. /**
  853. * 相除
  854. */
  855. ECFieldElementFp.prototype.divide = function divide(b) {
  856. return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q));
  857. };
  858. /**
  859. * 平方
  860. */
  861. ECFieldElementFp.prototype.square = function square() {
  862. return new ECFieldElementFp(this.q, this.x.square().mod(this.q));
  863. };
  864. return ECFieldElementFp;
  865. }();
  866. var ECPointFp = function () {
  867. function ECPointFp(curve, x, y, z) {
  868. _classCallCheck(this, ECPointFp);
  869. this.curve = curve;
  870. this.x = x;
  871. this.y = y;
  872. // 标准射影坐标系:zinv == null 或 z * zinv == 1
  873. this.z = z == null ? BigInteger.ONE : z;
  874. this.zinv = null;
  875. // TODO: compression flag
  876. }
  877. ECPointFp.prototype.getX = function getX() {
  878. if (this.zinv === null) this.zinv = this.z.modInverse(this.curve.q);
  879. return this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q));
  880. };
  881. ECPointFp.prototype.getY = function getY() {
  882. if (this.zinv === null) this.zinv = this.z.modInverse(this.curve.q);
  883. return this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q));
  884. };
  885. /**
  886. * 判断相等
  887. */
  888. ECPointFp.prototype.equals = function equals(other) {
  889. if (other === this) return true;
  890. if (this.isInfinity()) return other.isInfinity();
  891. if (other.isInfinity()) return this.isInfinity();
  892. // u = y2 * z1 - y1 * z2
  893. var u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q);
  894. if (!u.equals(BigInteger.ZERO)) return false;
  895. // v = x2 * z1 - x1 * z2
  896. var v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q);
  897. return v.equals(BigInteger.ZERO);
  898. };
  899. /**
  900. * 是否是无穷远点
  901. */
  902. ECPointFp.prototype.isInfinity = function isInfinity() {
  903. if (this.x === null && this.y === null) return true;
  904. return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO);
  905. };
  906. /**
  907. * 取反,x 轴对称点
  908. */
  909. ECPointFp.prototype.negate = function negate() {
  910. return new ECPointFp(this.curve, this.x, this.y.negate(), this.z);
  911. };
  912. /**
  913. * 相加
  914. *
  915. * 标准射影坐标系:
  916. *
  917. * λ1 = x1 * z2
  918. * λ2 = x2 * z1
  919. * λ3 = λ1 − λ2
  920. * λ4 = y1 * z2
  921. * λ5 = y2 * z1
  922. * λ6 = λ4 − λ5
  923. * λ7 = λ1 + λ2
  924. * λ8 = z1 * z2
  925. * λ9 = λ3^2
  926. * λ10 = λ3 * λ9
  927. * λ11 = λ8 * λ6^2 − λ7 * λ9
  928. * x3 = λ3 * λ11
  929. * y3 = λ6 * (λ9 * λ1 − λ11) − λ4 * λ10
  930. * z3 = λ10 * λ8
  931. */
  932. ECPointFp.prototype.add = function add(b) {
  933. if (this.isInfinity()) return b;
  934. if (b.isInfinity()) return this;
  935. var x1 = this.x.toBigInteger();
  936. var y1 = this.y.toBigInteger();
  937. var z1 = this.z;
  938. var x2 = b.x.toBigInteger();
  939. var y2 = b.y.toBigInteger();
  940. var z2 = b.z;
  941. var q = this.curve.q;
  942. var w1 = x1.multiply(z2).mod(q);
  943. var w2 = x2.multiply(z1).mod(q);
  944. var w3 = w1.subtract(w2);
  945. var w4 = y1.multiply(z2).mod(q);
  946. var w5 = y2.multiply(z1).mod(q);
  947. var w6 = w4.subtract(w5);
  948. if (BigInteger.ZERO.equals(w3)) {
  949. if (BigInteger.ZERO.equals(w6)) {
  950. return this.twice(); // this == b,计算自加
  951. }
  952. return this.curve.infinity; // this == -b,则返回无穷远点
  953. }
  954. var w7 = w1.add(w2);
  955. var w8 = z1.multiply(z2).mod(q);
  956. var w9 = w3.square().mod(q);
  957. var w10 = w3.multiply(w9).mod(q);
  958. var w11 = w8.multiply(w6.square()).subtract(w7.multiply(w9)).mod(q);
  959. var x3 = w3.multiply(w11).mod(q);
  960. var y3 = w6.multiply(w9.multiply(w1).subtract(w11)).subtract(w4.multiply(w10)).mod(q);
  961. var z3 = w10.multiply(w8).mod(q);
  962. return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
  963. };
  964. /**
  965. * 自加
  966. *
  967. * 标准射影坐标系:
  968. *
  969. * λ1 = 3 * x1^2 + a * z1^2
  970. * λ2 = 2 * y1 * z1
  971. * λ3 = y1^2
  972. * λ4 = λ3 * x1 * z1
  973. * λ5 = λ2^2
  974. * λ6 = λ1^2 − 8 * λ4
  975. * x3 = λ2 * λ6
  976. * y3 = λ1 * (4 * λ4 − λ6) − 2 * λ5 * λ3
  977. * z3 = λ2 * λ5
  978. */
  979. ECPointFp.prototype.twice = function twice() {
  980. if (this.isInfinity()) return this;
  981. if (!this.y.toBigInteger().signum()) return this.curve.infinity;
  982. var x1 = this.x.toBigInteger();
  983. var y1 = this.y.toBigInteger();
  984. var z1 = this.z;
  985. var q = this.curve.q;
  986. var a = this.curve.a.toBigInteger();
  987. var w1 = x1.square().multiply(THREE).add(a.multiply(z1.square())).mod(q);
  988. var w2 = y1.shiftLeft(1).multiply(z1).mod(q);
  989. var w3 = y1.square().mod(q);
  990. var w4 = w3.multiply(x1).multiply(z1).mod(q);
  991. var w5 = w2.square().mod(q);
  992. var w6 = w1.square().subtract(w4.shiftLeft(3)).mod(q);
  993. var x3 = w2.multiply(w6).mod(q);
  994. var y3 = w1.multiply(w4.shiftLeft(2).subtract(w6)).subtract(w5.shiftLeft(1).multiply(w3)).mod(q);
  995. var z3 = w2.multiply(w5).mod(q);
  996. return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
  997. };
  998. /**
  999. * 倍点计算
  1000. */
  1001. ECPointFp.prototype.multiply = function multiply(k) {
  1002. if (this.isInfinity()) return this;
  1003. if (!k.signum()) return this.curve.infinity;
  1004. // 使用加减法
  1005. var k3 = k.multiply(THREE);
  1006. var neg = this.negate();
  1007. var Q = this;
  1008. for (var i = k3.bitLength() - 2; i > 0; i--) {
  1009. Q = Q.twice();
  1010. var k3Bit = k3.testBit(i);
  1011. var kBit = k.testBit(i);
  1012. if (k3Bit !== kBit) {
  1013. Q = Q.add(k3Bit ? this : neg);
  1014. }
  1015. }
  1016. return Q;
  1017. };
  1018. return ECPointFp;
  1019. }();
  1020. /**
  1021. * 椭圆曲线 y^2 = x^3 + ax + b
  1022. */
  1023. var ECCurveFp = function () {
  1024. function ECCurveFp(q, a, b) {
  1025. _classCallCheck(this, ECCurveFp);
  1026. this.q = q;
  1027. this.a = this.fromBigInteger(a);
  1028. this.b = this.fromBigInteger(b);
  1029. this.infinity = new ECPointFp(this, null, null); // 无穷远点
  1030. }
  1031. /**
  1032. * 判断两个椭圆曲线是否相等
  1033. */
  1034. ECCurveFp.prototype.equals = function equals(other) {
  1035. if (other === this) return true;
  1036. return this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b);
  1037. };
  1038. /**
  1039. * 生成椭圆曲线域元素
  1040. */
  1041. ECCurveFp.prototype.fromBigInteger = function fromBigInteger(x) {
  1042. return new ECFieldElementFp(this.q, x);
  1043. };
  1044. /**
  1045. * 解析 16 进制串为椭圆曲线点
  1046. */
  1047. ECCurveFp.prototype.decodePointHex = function decodePointHex(s) {
  1048. switch (parseInt(s.substr(0, 2), 16)) {
  1049. // 第一个字节
  1050. case 0:
  1051. return this.infinity;
  1052. case 2:
  1053. case 3:
  1054. // 不支持的压缩方式
  1055. return null;
  1056. case 4:
  1057. case 6:
  1058. case 7:
  1059. var len = (s.length - 2) / 2;
  1060. var xHex = s.substr(2, len);
  1061. var yHex = s.substr(len + 2, len);
  1062. return new ECPointFp(this, this.fromBigInteger(new BigInteger(xHex, 16)), this.fromBigInteger(new BigInteger(yHex, 16)));
  1063. default:
  1064. // 不支持
  1065. return null;
  1066. }
  1067. };
  1068. return ECCurveFp;
  1069. }();
  1070. module.exports = {
  1071. ECPointFp: ECPointFp,
  1072. ECCurveFp: ECCurveFp
  1073. };
  1074. /***/ }),
  1075. /* 7 */
  1076. /***/ (function(module, exports, __webpack_require__) {
  1077. "use strict";
  1078. var sm3 = __webpack_require__(1);
  1079. /**
  1080. * 字节数组转 16 进制串
  1081. */
  1082. function ArrayToHex(arr) {
  1083. return arr.map(function (item) {
  1084. item = item.toString(16);
  1085. return item.length === 1 ? '0' + item : item;
  1086. }).join('');
  1087. }
  1088. /**
  1089. * utf8 串转字节数组
  1090. */
  1091. function utf8ToArray(str) {
  1092. var arr = [];
  1093. for (var i = 0, len = str.length; i < len; i++) {
  1094. var point = str.codePointAt(i);
  1095. if (point <= 0x007f) {
  1096. // 单字节,标量值:00000000 00000000 0zzzzzzz
  1097. arr.push(point);
  1098. } else if (point <= 0x07ff) {
  1099. // 双字节,标量值:00000000 00000yyy yyzzzzzz
  1100. arr.push(0xc0 | point >>> 6); // 110yyyyy(0xc0-0xdf)
  1101. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1102. } else if (point <= 0xD7FF || point >= 0xE000 && point <= 0xFFFF) {
  1103. // 三字节:标量值:00000000 xxxxyyyy yyzzzzzz
  1104. arr.push(0xe0 | point >>> 12); // 1110xxxx(0xe0-0xef)
  1105. arr.push(0x80 | point >>> 6 & 0x3f); // 10yyyyyy(0x80-0xbf)
  1106. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1107. } else if (point >= 0x010000 && point <= 0x10FFFF) {
  1108. // 四字节:标量值:000wwwxx xxxxyyyy yyzzzzzz
  1109. i++;
  1110. arr.push(0xf0 | point >>> 18 & 0x1c); // 11110www(0xf0-0xf7)
  1111. arr.push(0x80 | point >>> 12 & 0x3f); // 10xxxxxx(0x80-0xbf)
  1112. arr.push(0x80 | point >>> 6 & 0x3f); // 10yyyyyy(0x80-0xbf)
  1113. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1114. } else {
  1115. // 五、六字节,暂时不支持
  1116. arr.push(point);
  1117. throw new Error('input is not supported');
  1118. }
  1119. }
  1120. return arr;
  1121. }
  1122. module.exports = function (input) {
  1123. input = typeof input === 'string' ? utf8ToArray(input) : Array.prototype.slice.call(input);
  1124. return ArrayToHex(sm3(input));
  1125. };
  1126. /***/ }),
  1127. /* 8 */
  1128. /***/ (function(module, exports, __webpack_require__) {
  1129. "use strict";
  1130. /* eslint-disable no-bitwise, no-mixed-operators, complexity */
  1131. var DECRYPT = 0;
  1132. var ROUND = 32;
  1133. var BLOCK = 16;
  1134. 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];
  1135. 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];
  1136. /**
  1137. * 16 进制串转字节数组
  1138. */
  1139. function hexToArray(str) {
  1140. var arr = [];
  1141. for (var i = 0, len = str.length; i < len; i += 2) {
  1142. arr.push(parseInt(str.substr(i, 2), 16));
  1143. }
  1144. return arr;
  1145. }
  1146. /**
  1147. * 字节数组转 16 进制串
  1148. */
  1149. function ArrayToHex(arr) {
  1150. return arr.map(function (item) {
  1151. item = item.toString(16);
  1152. return item.length === 1 ? '0' + item : item;
  1153. }).join('');
  1154. }
  1155. /**
  1156. * utf8 串转字节数组
  1157. */
  1158. function utf8ToArray(str) {
  1159. var arr = [];
  1160. for (var i = 0, len = str.length; i < len; i++) {
  1161. var point = str.codePointAt(i);
  1162. if (point <= 0x007f) {
  1163. // 单字节,标量值:00000000 00000000 0zzzzzzz
  1164. arr.push(point);
  1165. } else if (point <= 0x07ff) {
  1166. // 双字节,标量值:00000000 00000yyy yyzzzzzz
  1167. arr.push(0xc0 | point >>> 6); // 110yyyyy(0xc0-0xdf)
  1168. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1169. } else if (point <= 0xD7FF || point >= 0xE000 && point <= 0xFFFF) {
  1170. // 三字节:标量值:00000000 xxxxyyyy yyzzzzzz
  1171. arr.push(0xe0 | point >>> 12); // 1110xxxx(0xe0-0xef)
  1172. arr.push(0x80 | point >>> 6 & 0x3f); // 10yyyyyy(0x80-0xbf)
  1173. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1174. } else if (point >= 0x010000 && point <= 0x10FFFF) {
  1175. // 四字节:标量值:000wwwxx xxxxyyyy yyzzzzzz
  1176. i++;
  1177. arr.push(0xf0 | point >>> 18 & 0x1c); // 11110www(0xf0-0xf7)
  1178. arr.push(0x80 | point >>> 12 & 0x3f); // 10xxxxxx(0x80-0xbf)
  1179. arr.push(0x80 | point >>> 6 & 0x3f); // 10yyyyyy(0x80-0xbf)
  1180. arr.push(0x80 | point & 0x3f); // 10zzzzzz(0x80-0xbf)
  1181. } else {
  1182. // 五、六字节,暂时不支持
  1183. arr.push(point);
  1184. throw new Error('input is not supported');
  1185. }
  1186. }
  1187. return arr;
  1188. }
  1189. /**
  1190. * 字节数组转 utf8 串
  1191. */
  1192. function arrayToUtf8(arr) {
  1193. var str = [];
  1194. for (var i = 0, len = arr.length; i < len; i++) {
  1195. if (arr[i] >= 0xf0 && arr[i] <= 0xf7) {
  1196. // 四字节
  1197. str.push(String.fromCodePoint(((arr[i] & 0x07) << 18) + ((arr[i + 1] & 0x3f) << 12) + ((arr[i + 2] & 0x3f) << 6) + (arr[i + 3] & 0x3f)));
  1198. i += 3;
  1199. } else if (arr[i] >= 0xe0 && arr[i] <= 0xef) {
  1200. // 三字节
  1201. str.push(String.fromCodePoint(((arr[i] & 0x0f) << 12) + ((arr[i + 1] & 0x3f) << 6) + (arr[i + 2] & 0x3f)));
  1202. i += 2;
  1203. } else if (arr[i] >= 0xc0 && arr[i] <= 0xdf) {
  1204. // 双字节
  1205. str.push(String.fromCodePoint(((arr[i] & 0x1f) << 6) + (arr[i + 1] & 0x3f)));
  1206. i++;
  1207. } else {
  1208. // 单字节
  1209. str.push(String.fromCodePoint(arr[i]));
  1210. }
  1211. }
  1212. return str.join('');
  1213. }
  1214. /**
  1215. * 32 比特循环左移
  1216. */
  1217. function rotl(x, y) {
  1218. return x << y | x >>> 32 - y;
  1219. }
  1220. /**
  1221. * 非线性变换
  1222. */
  1223. function byteSub(a) {
  1224. return (Sbox[a >>> 24 & 0xFF] & 0xFF) << 24 | (Sbox[a >>> 16 & 0xFF] & 0xFF) << 16 | (Sbox[a >>> 8 & 0xFF] & 0xFF) << 8 | Sbox[a & 0xFF] & 0xFF;
  1225. }
  1226. /**
  1227. * 线性变换,加密/解密用
  1228. */
  1229. function l1(b) {
  1230. return b ^ rotl(b, 2) ^ rotl(b, 10) ^ rotl(b, 18) ^ rotl(b, 24);
  1231. }
  1232. /**
  1233. * 线性变换,生成轮密钥用
  1234. */
  1235. function l2(b) {
  1236. return b ^ rotl(b, 13) ^ rotl(b, 23);
  1237. }
  1238. /**
  1239. * 以一组 128 比特进行加密/解密操作
  1240. */
  1241. function sms4Crypt(input, output, roundKey) {
  1242. var x = new Array(4);
  1243. // 字节数组转成字数组(此处 1 字 = 32 比特)
  1244. var tmp = new Array(4);
  1245. for (var i = 0; i < 4; i++) {
  1246. tmp[0] = input[4 * i] & 0xff;
  1247. tmp[1] = input[4 * i + 1] & 0xff;
  1248. tmp[2] = input[4 * i + 2] & 0xff;
  1249. tmp[3] = input[4 * i + 3] & 0xff;
  1250. x[i] = tmp[0] << 24 | tmp[1] << 16 | tmp[2] << 8 | tmp[3];
  1251. }
  1252. // x[i + 4] = x[i] ^ l1(byteSub(x[i + 1] ^ x[i + 2] ^ x[i + 3] ^ roundKey[i]))
  1253. for (var r = 0, mid; r < 32; r += 4) {
  1254. mid = x[1] ^ x[2] ^ x[3] ^ roundKey[r + 0];
  1255. x[0] ^= l1(byteSub(mid)); // x[4]
  1256. mid = x[2] ^ x[3] ^ x[0] ^ roundKey[r + 1];
  1257. x[1] ^= l1(byteSub(mid)); // x[5]
  1258. mid = x[3] ^ x[0] ^ x[1] ^ roundKey[r + 2];
  1259. x[2] ^= l1(byteSub(mid)); // x[6]
  1260. mid = x[0] ^ x[1] ^ x[2] ^ roundKey[r + 3];
  1261. x[3] ^= l1(byteSub(mid)); // x[7]
  1262. }
  1263. // 反序变换
  1264. for (var j = 0; j < 16; j += 4) {
  1265. output[j] = x[3 - j / 4] >>> 24 & 0xff;
  1266. output[j + 1] = x[3 - j / 4] >>> 16 & 0xff;
  1267. output[j + 2] = x[3 - j / 4] >>> 8 & 0xff;
  1268. output[j + 3] = x[3 - j / 4] & 0xff;
  1269. }
  1270. }
  1271. /**
  1272. * 密钥扩展算法
  1273. */
  1274. function sms4KeyExt(key, roundKey, cryptFlag) {
  1275. var x = new Array(4);
  1276. // 字节数组转成字数组(此处 1 字 = 32 比特)
  1277. var tmp = new Array(4);
  1278. for (var i = 0; i < 4; i++) {
  1279. tmp[0] = key[0 + 4 * i] & 0xff;
  1280. tmp[1] = key[1 + 4 * i] & 0xff;
  1281. tmp[2] = key[2 + 4 * i] & 0xff;
  1282. tmp[3] = key[3 + 4 * i] & 0xff;
  1283. x[i] = tmp[0] << 24 | tmp[1] << 16 | tmp[2] << 8 | tmp[3];
  1284. }
  1285. // 与系统参数做异或
  1286. x[0] ^= 0xa3b1bac6;
  1287. x[1] ^= 0x56aa3350;
  1288. x[2] ^= 0x677d9197;
  1289. x[3] ^= 0xb27022dc;
  1290. // roundKey[i] = x[i + 4] = x[i] ^ l2(byteSub(x[i + 1] ^ x[i + 2] ^ x[i + 3] ^ CK[i]))
  1291. for (var r = 0, mid; r < 32; r += 4) {
  1292. mid = x[1] ^ x[2] ^ x[3] ^ CK[r + 0];
  1293. roundKey[r + 0] = x[0] ^= l2(byteSub(mid)); // x[4]
  1294. mid = x[2] ^ x[3] ^ x[0] ^ CK[r + 1];
  1295. roundKey[r + 1] = x[1] ^= l2(byteSub(mid)); // x[5]
  1296. mid = x[3] ^ x[0] ^ x[1] ^ CK[r + 2];
  1297. roundKey[r + 2] = x[2] ^= l2(byteSub(mid)); // x[6]
  1298. mid = x[0] ^ x[1] ^ x[2] ^ CK[r + 3];
  1299. roundKey[r + 3] = x[3] ^= l2(byteSub(mid)); // x[7]
  1300. }
  1301. // 解密时使用反序的轮密钥
  1302. if (cryptFlag === DECRYPT) {
  1303. for (var _r = 0, _mid; _r < 16; _r++) {
  1304. _mid = roundKey[_r];
  1305. roundKey[_r] = roundKey[31 - _r];
  1306. roundKey[31 - _r] = _mid;
  1307. }
  1308. }
  1309. }
  1310. function sm4(inArray, key, cryptFlag) {
  1311. var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {},
  1312. _ref$padding = _ref.padding,
  1313. padding = _ref$padding === undefined ? 'pkcs#5' : _ref$padding,
  1314. mode = _ref.mode,
  1315. _ref$iv = _ref.iv,
  1316. iv = _ref$iv === undefined ? [] : _ref$iv,
  1317. _ref$output = _ref.output,
  1318. output = _ref$output === undefined ? 'string' : _ref$output;
  1319. if (mode === 'cbc') {
  1320. // @TODO,CBC 模式,默认走 ECB 模式
  1321. if (typeof iv === 'string') iv = hexToArray(iv);
  1322. if (iv.length !== 128 / 8) {
  1323. // iv 不是 128 比特
  1324. throw new Error('iv is invalid');
  1325. }
  1326. }
  1327. // 检查 key
  1328. if (typeof key === 'string') key = hexToArray(key);
  1329. if (key.length !== 128 / 8) {
  1330. // key 不是 128 比特
  1331. throw new Error('key is invalid');
  1332. }
  1333. // 检查输入
  1334. if (typeof inArray === 'string') {
  1335. if (cryptFlag !== DECRYPT) {
  1336. // 加密,输入为 utf8 串
  1337. inArray = utf8ToArray(inArray);
  1338. } else {
  1339. // 解密,输入为 16 进制串
  1340. inArray = hexToArray(inArray);
  1341. }
  1342. } else {
  1343. inArray = [].concat(inArray);
  1344. }
  1345. // 新增填充
  1346. if (padding === 'pkcs#5' && cryptFlag !== DECRYPT) {
  1347. var paddingCount = BLOCK - inArray.length % BLOCK;
  1348. for (var i = 0; i < paddingCount; i++) {
  1349. inArray.push(paddingCount);
  1350. }
  1351. }
  1352. // 生成轮密钥
  1353. var roundKey = new Array(ROUND);
  1354. sms4KeyExt(key, roundKey, cryptFlag);
  1355. var outArray = [];
  1356. var lastVector = iv;
  1357. var restLen = inArray.length;
  1358. var point = 0;
  1359. while (restLen >= BLOCK) {
  1360. var input = inArray.slice(point, point + 16);
  1361. var _output = new Array(16);
  1362. if (mode === 'cbc') {
  1363. for (var _i = 0; _i < BLOCK; _i++) {
  1364. if (cryptFlag !== DECRYPT) {
  1365. // 加密过程在组加密前进行异或
  1366. input[_i] ^= lastVector[_i];
  1367. }
  1368. }
  1369. }
  1370. sms4Crypt(input, _output, roundKey);
  1371. for (var _i2 = 0; _i2 < BLOCK; _i2++) {
  1372. if (mode === 'cbc') {
  1373. if (cryptFlag === DECRYPT) {
  1374. // 解密过程在组解密后进行异或
  1375. _output[_i2] ^= lastVector[_i2];
  1376. }
  1377. }
  1378. outArray[point + _i2] = _output[_i2];
  1379. }
  1380. if (mode === 'cbc') {
  1381. if (cryptFlag !== DECRYPT) {
  1382. // 使用上一次输出作为加密向量
  1383. lastVector = _output;
  1384. } else {
  1385. // 使用上一次输入作为解密向量
  1386. lastVector = input;
  1387. }
  1388. }
  1389. restLen -= BLOCK;
  1390. point += BLOCK;
  1391. }
  1392. // 去除填充
  1393. if (padding === 'pkcs#5' && cryptFlag === DECRYPT) {
  1394. var _paddingCount = outArray[outArray.length - 1];
  1395. outArray.splice(outArray.length - _paddingCount, _paddingCount);
  1396. }
  1397. // 调整输出
  1398. if (output !== 'array') {
  1399. if (cryptFlag !== DECRYPT) {
  1400. // 加密,输出转 16 进制串
  1401. return ArrayToHex(outArray);
  1402. } else {
  1403. // 解密,输出转 utf8 串
  1404. return arrayToUtf8(outArray);
  1405. }
  1406. } else {
  1407. return outArray;
  1408. }
  1409. }
  1410. module.exports = {
  1411. encrypt: function encrypt(inArray, key, options) {
  1412. return sm4(inArray, key, 1, options);
  1413. },
  1414. decrypt: function decrypt(inArray, key, options) {
  1415. return sm4(inArray, key, 0, options);
  1416. }
  1417. };
  1418. /***/ })
  1419. /******/ ]);