安裝sm-crypto
npm install --save sm-crypto
參考一
const sm4 = require('sm-crypto').sm4;
import { Base64 } from 'js-base64'
// const key = 'facca33012345678facca33012345678' // 32字節 可以為 16 進制串或字節數組,要求為 128 比特
const key = '2YvDpbp6OwqZuxVF'
//base64轉為16進制
function base64ToHex(base64) {
const bytes = window.atob(base64)
let hex = ''
for (let i = 0; i < bytes.length; i++) {
const byte = bytes.charCodeAt(i).toString(16)
hex += byte.padStart(2, '0')
}
return hex
}
//將key加密并返回16進制
function changeKey() {
const encodeBase64 = Base64.encode(key) //base64加密
const hex = base64ToHex(encodeBase64)
return hex
}
/*
* text 待加密文本
*/
export function encrypt(text) {
const params = JSON.stringify(text)
const encrypt = sm4.encrypt(params, changeKey())
return encrypt
}
/*
* text 待解密密文
*/
export function decrypt(text) {
const decrypt = sm4.decrypt(text, changeKey()) // 加密,不使用 padding,輸出16進制字符串
return decrypt
}
export default {
encrypt,
decrypt
}
參考二:
const sm4 = require('sm-crypto').sm4
const msg = 'hello world! 我是 juneandgreen.' // 可以為 utf8 串或字節數組
const key = '0123456789abcdeffedcba9876543210' // 可以為 16 進制串或字節數組,要求為 128 比特
let encryptData = sm4.encrypt(msg, key) // 加密,默認輸出 16 進制字符串,默認使用 pkcs#7 填充(傳 pkcs#5 也會走 pkcs#7 填充)
let encryptData = sm4.encrypt(msg, key, {padding: 'none'}) // 加密,不使用 padding
let encryptData = sm4.encrypt(msg, key, {padding: 'none', output: 'array'}) // 加密,不使用 padding,輸出為字節數組
let encryptData = sm4.encrypt(msg, key, {mode: 'cbc', iv: 'fedcba98765432100123456789abcdef'}) // 加密,cbc 模式
簽名/驗簽
簽名:
const { sm2 } = require('sm-crypto');
const keyPair = sm2.generateKeyPairHex(); // 生成密鑰對
const publicKey = keyPair.publicKey; // 公鑰
const privateKey = keyPair.privateKey; // 私鑰
const message = '這是要簽名的消息'; // 替換為實際要簽名的消息
// 使用私鑰對消息進行簽名
let sigValueHex = sm2.doSignature(message, privateKey);
console.log('簽名結果:', sigValueHex);
驗簽
const message = '這是要驗證簽名的消息'; // 應與簽名時使用的消息相同 const sigValueHex = '簽名值'; // 替換為實際的簽名值字符串,即簽名步驟中生成的sigValueHex // 使用公鑰驗證簽名是否有效 let verifyResult = sm2.doVerifySignature(message, sigValueHex, publicKey); console.log('驗簽結果:', verifyResult); // 如果驗證成功,應輸出true;否則輸出false
浙公網安備 33010602011771號