Home

国密sm2

# 安装

sm-crypto (opens new window)

npm install --save sm-crypto

# 使用

import smCrypto from 'sm-crypto'
const publicKey = 'xxxxxxxxxxx'
const privatekey = 'xxxxx'

//加密
const smString = '04' + smCrypto.sm2.doEncrypt('要加密的字符串', publicKey, 1)

//规则
//smCrypto.sm2.doEncrypt(msgString, publicKey, cipherMode) 
//const cipherMode = 1 // 1 - C1C3C2,0 - C1C2C3,默认为1

//解密
smCrypto.sm2.doDecrypt(smString.replace(/^04/,''),privatekey,1)
//因为04是拼接的,所以解密的时候要去掉
//拼接04的原因是后端需要补位,必须拼接04

# 生成密钥

正常开发公钥和私钥后端生成,然后发给前端,保持一致

let keypair = smCrypto.sm2.generateKeyPairHex()
publicKey = keypair.publicKey // 公钥
privateKey = keypair.privateKey // 私钥