index.js 43 KB

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