随笔 - 48,  文章 - 1,  评论 - 7,  阅读 - 10万
安装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   铭の  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

友情链接:箫竹影(Java工程师)
点击右上角即可分享
微信分享提示