Closed bh4rtp closed 2 years ago
node.js测试代码:
const { SM2 } = require('gm-crypto')
const { publicKey, privateKey } = SM2.generateKeyPair()
const originalData = 'SM2 Algorithm'
console.log(publicKey);
console.log(privateKey);
const encryptedData = SM2.encrypt(originalData, publicKey, {
inputEncoding: 'utf8',
outputEncoding: 'base64',
mode: 'C1C3C2'
})
console.log(encryptedData); // publicKey, privateKey, encryptedData提供给gmsm解密
const decryptedData = SM2.decrypt(encryptedData, privateKey, {
inputEncoding: 'base64',
outputEncoding: 'utf8',
mode: 'C1C3C2'
})
console.log(decryptedData);
golang测试代码:
import (
"encoding/base64"
"fmt"
"github.com/tjfoc/gmsm/sm2"
"math/big"
"strings"
)
func generateSM2Keys(privateKeyStr, publicKeyStr string) (*sm2.PublicKey, *sm2.PrivateKey) {
publicKey := generateSM2PublicKey(publicKeyStr)
privateKeyStr = strings.TrimLeft(privateKeyStr, "0")
d, _ := new(big.Int).SetString(privateKeyStr[:], 16)
privateKey := &sm2.PrivateKey{
PublicKey: *publicKey,
D: d,
}
return publicKey, privateKey
}
func generateSM2PublicKey(publicKeyStr string) *sm2.PublicKey {
publicKeyStr = strings.TrimLeft(strings.TrimPrefix(publicKeyStr, "04"), "0")
x, _ := new(big.Int).SetString(publicKeyStr[0:64], 16)
y, _ := new(big.Int).SetString(publicKeyStr[64:], 16)
return &sm2.PublicKey{
Curve: sm2.P256Sm2(),
X: x,
Y: y,
}
}
func main() {
pubKeyStr := "0415af270dd4fc0f466a1c216700a95ee61624bec779e4069017e822b588a4f94cb28c7bf13fe77f39c61a5f351881702babe4a6673221369a3f6ec015e416806c"
priKeyStr := "b0ddcacb1298e68be276abec9a260740d45dcbb879dce0240ff03185b11d197b"
encryptedData := "Y3yYFxgGvqyjf6E/riw0AAR5ynRO17/Z3OwacPvMe+e6nQ2TnKYPGo8Nq829NQCqZUuzAs+V1Z0BcKnsBorv8hHtQJ7jhkOMYFAbfQljH2SQQqbErT+0Nhep34TXtnrQopm9RHTag/tcvB51+g=="
_, priKey := generateSM2Keys(priKeyStr, pubKeyStr)
encryptedBytes, err := base64.StdEncoding.DecodeString(encryptedData)
decryptedData, err := sm2.Decrypt(priKey, encryptedBytes, sm2.C1C3C2)
fmt.Printf("clear text = %s\n", decryptedData)
}
Add prefix of byte(0x04)
to your encrypted data.
我用的node.js国密库是gm-crypto 0.1.18,node.js生成的密钥对: 公钥: 0415af270dd4fc0f466a1c216700a95ee61624bec779e4069017e822b588a4f94cb28c7bf13fe77f39c61a5f351881702babe4a6673221369a3f6ec015e416806c 私钥: b0ddcacb1298e68be276abec9a260740d45dcbb879dce0240ff03185b11d197b 密文(base64): Y3yYFxgGvqyjf6E/riw0AAR5ynRO17/Z3OwacPvMe+e6nQ2TnKYPGo8Nq829NQCqZUuzAs+V1Z0BcKnsBorv8hHtQJ7jhkOMYFAbfQljH2SQQqbErT+0Nhep34TXtnrQopm9RHTag/tcvB51+g== 哪位成功对接过node.js与golang的国密库,请指点,谢谢?