安装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

 

posted on 2025-01-07 17:48  铭の  阅读(139)  评论(0)    收藏  举报

友情链接:箫竹影(Java工程师)