vue前端国密SM2, SM4 算法实现

vue前端国密SM2, SM4 算法实现

整体加密逻辑是,首先生成16位key值 用SM2 公钥加密该key值,后端用sm2私钥 解密出key值,然后采用sm4方法根据key值对返回值进行加密,前端采用sm4 对后端返回结果进行解密进行前端展示

目前主要常用的国密算法有sm-crypto,gm-crypto,gm-crypt(SM4)

SM2+ sm-crypto

1、安装sm-crypto
npm install --save sm-crypto
2、包装加解密方法

const sm2 = require('sm-crypto').sm2
// 获取密钥对
// let keypair = sm2.generateKeyPairHex()
// const publicKey = keypair.publicKey // 公钥
// const privateKey = keypair.privateKey // 私钥

// 和后端约定得密钥对公钥  如公钥字符串前面无04需加上04
const publicKey = ‘04xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

// sm2 加密
export const rsaPublicData = function (data) {
  const cipherMode = 1
  const result = sm2.doEncrypt(data, publicKey, cipherMode)
  return result
}

// sm-  解密
export const rsaPublicData1 = function (data) {
  const cipherMode = 1
  const result = sm2.doDecrypt(data, privateKey, cipherMode)
  return result
}

sm2+gm-crypto

1、安装gm-crypto
npm install --save gm-crypto
2、包装加解密方法

import { SM2 } from 'gm-crypto'
// 获取密钥对
/// const { publicKey, privateKey } = SM2.generateKeyPair()

// 和后端约定得密钥对公钥  如公钥字符串前面无04需加上04
const publicKey = ‘04xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

// gm0 sm2
export const rsaPublicData = function (data) {
  const cipherMode = {
    inputEncoding: 'utf8',
    outputEncoding: 'base64'

  }
  const result = SM2.encrypt(data, publicKey, cipherMode)
  return result
}

// sm-  解密
export const rsaPublicData1 = function (data) {
  const cipherMode = {
    inputEncoding: 'base64',
    outputEncoding: 'utf8'
  }
  const result = SM2.decrypt(data, privateKey, cipherMode)
  return result
}

sm4+gm-crypt

1、安装gm-crypt
npm install --save gm-crypt
2、包装加解密方法

const SM4 = require('gm-crypt').sm4


// 加密
export const Encrypt = (word, key) => {
  const sm4Config = {
    key,
    mode: 'ecb',
    cipherType: 'base64'
  }
  const sm4 = new SM4(sm4Config)
  const ecryptedStr = sm4.encrypt(word)
  return ecryptedStr
}

// 解密
export const Decrypt = (word, key) => {
  const sm4Config = {
    key,
    mode: 'ecb',
    cipherType: 'base64'
  }
  const sm4 = new SM4(sm4Config)
  const decryptedStr = sm4.decrypt(word)
  return decryptedStr
}

具体接口中应用

在公司项目中采用的是gm-crypto中的sm2和 gm-crypt 中的sm4
具体对应的算法需要和后端选取的对应

let keys = nanoid(16)  //采用nanoid生成16位字符串

// 举例在接口getInfo中的应用,encryptedStr是和后端约定的字段名称

getInfo({encryptedStr: rsaPublicData(keys)}).then(res=> {
const data = JSON.parse(Decrypt(res.result, keys))   // 对后端返回的数据进行解密,转化成json格式
)

参考资料
https://www.npmjs.com/package/sm-crypto
https://www.npmjs.com/package/sm-crypto
https://www.npmjs.com/package/gm-crypt

  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值