sm-crypto
国密算法sm2、sm3和sm4的js版。
PS: 小程序移植版:https://github.com/wechat-miniprogram/sm-crypto
安装
npm install --save sm-crypto
sm2
获取密钥对
const sm2 = require('sm-crypto').sm2
let keypair = sm2.generateKeyPairHex()
publicKey = keypair.publicKey
privateKey = keypair.privateKey
加密解密
const sm2 = require('sm-crypto').sm2
const cipherMode = 1
let encryptData = sm2.doEncrypt(msgString, publicKey, cipherMode)
let decryptData = sm2.doDecrypt(encryptData, privateKey, cipherMode)
签名验签
ps:理论上来说,只做纯签名是最快的。
const sm2 = require('sm-crypto').sm2
let sigValueHex = sm2.doSignature(msg, privateKey)
let verifyResult = sm2.doVerifySignature(msg, sigValueHex, publicKey)
let sigValueHex2 = sm2.doSignature(msg, privateKey, {
pointPool: [sm2.getPoint(), sm2.getPoint(), sm2.getPoint(), sm2.getPoint()],
})
let verifyResult2 = sm2.doVerifySignature(msg, sigValueHex2, publicKey)
let sigValueHex3 = sm2.doSignature(msg, privateKey, {
der: true,
})
let verifyResult3 = sm2.doVerifySignature(msg, sigValueHex3, publicKey, {
der: true,
})
let sigValueHex4 = sm2.doSignature(msg, privateKey, {
hash: true,
})
let verifyResult4 = sm2.doVerifySignature(msg, sigValueHex4, publicKey, {
hash: true,
})
let sigValueHex5 = sm2.doSignature(msg, privateKey, {
hash: true,
publicKey,
})
let verifyResult5 = sm2.doVerifySignature(msg, sigValueHex5, publicKey, {
hash: true,
publicKey,
})
let sigValueHex6 = sm2.doSignature(msgString, privateKey, {
hash: true,
publicKey,
userId: 'testUserId',
})
let verifyResult6 = sm2.doVerifySignature(msgString, sigValueHex6, publicKey, {
hash: true,
userId: 'testUserId',
})
获取椭圆曲线点
const sm2 = require('sm-crypto').sm2
let poin = sm2.getPoint()
sm3
const sm3 = require('sm-crypto').sm3
let hashData = sm3('abc')
sm4
加密
const sm4 = require('sm-crypto').sm4
const key = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10]
let encryptData = sm4.encrypt([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10], key)
解密
const sm4 = require('sm-crypto').sm4
const key = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10]
let decryptData = sm4.decrypt([0x68, 0x1e, 0xdf, 0x34, 0xd2, 0x06, 0x96, 0x5e, 0x86, 0xb3, 0xe9, 0x4f, 0x53, 0x6e, 0x42, 0x46], key)
协议
MIT