diff --git a/src/sm2/asn1.js b/src/sm2/asn1.js index 051222c..566e45c 100755 --- a/src/sm2/asn1.js +++ b/src/sm2/asn1.js @@ -78,7 +78,18 @@ class DERInteger extends ASN1Object { return this.v } } +class DEROctetString extends ASN1Object { + constructor(s) { + super() + + this.t = '04' // octstr 标签说明 + if (s) this.v = s.toLowerCase() + } + getValue() { + return this.v + } +} class DERSequence extends ASN1Object { constructor(asn1Array) { super() @@ -134,6 +145,14 @@ module.exports = { return derSeq.getEncodedHex() }, + encodeEnc(x, y, hash, cipher) { + const derX = new DERInteger(x) + const derY = new DERInteger(y) + const derHash = new DEROctetString(hash) + const derCipher = new DEROctetString(cipher) + const derSeq = new DERSequence([derX, derY, derHash, derCipher]) + return derSeq.getEncodedHex() + }, /** * 解析 ASN.1 der,针对 sm2 验签 diff --git a/src/sm2/index.js b/src/sm2/index.js index c08e759..32d189f 100644 --- a/src/sm2/index.js +++ b/src/sm2/index.js @@ -1,6 +1,6 @@ /* eslint-disable no-use-before-define */ const {BigInteger} = require('jsbn') -const {encodeDer, decodeDer} = require('./asn1') +const {encodeDer, decodeDer, encodeEnc} = require('./asn1') const _ = require('./utils') const sm3 = require('./sm3').sm3 @@ -10,7 +10,7 @@ const C1C2C3 = 0 /** * 加密 */ -function doEncrypt(msg, publicKey, cipherMode = 1) { +function doEncrypt(msg, publicKey, cipherMode = 1, asn1 = false) { msg = typeof msg === 'string' ? _.hexToArray(_.utf8ToHex(msg)) : Array.prototype.slice.call(msg) publicKey = _.getGlobalCurve().decodePointHex(publicKey) // 先将公钥转成点 @@ -50,8 +50,12 @@ function doEncrypt(msg, publicKey, cipherMode = 1) { msg[i] ^= t[offset++] & 0xff } const c2 = _.arrayToHex(msg) - - return cipherMode === C1C2C3 ? c1 + c2 + c3 : c1 + c3 + c2 + if (asn1) { + const { Px, Py } = keypair + return cipherMode === C1C2C3 ? encodeEnc(Px, Py, c2, c3) : encodeEnc(Px, Py, c3, c2) + } else { + return cipherMode === C1C2C3 ? c1 + c2 + c3 : c1 + c3 + c2 + } } /** diff --git a/src/sm2/utils.js b/src/sm2/utils.js index 196659b..e528860 100644 --- a/src/sm2/utils.js +++ b/src/sm2/utils.js @@ -45,7 +45,7 @@ function generateKeyPairHex(a, b, c) { const Py = leftPad(P.getY().toBigInteger().toString(16), 64) const publicKey = '04' + Px + Py - return {privateKey, publicKey} + return {privateKey, publicKey, Px, Py} } /**