Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/sm2/asn1.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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 验签
Expand Down
12 changes: 8 additions & 4 deletions src/sm2/index.js
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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) // 先将公钥转成点

Expand Down Expand Up @@ -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
}
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/sm2/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}
}

/**
Expand Down