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

你可能感兴趣的:(前端,vue,前端,vue.js,javascript)