vue中使用国密算法SM2、SM3、SM4

1、安装包

npm install gm-crypto

2、引入包

import { SM4, SM3, SM2 } from 'gm-crypto';

3、SM2加密解密

let SM2Data = reactive({
  publicKey: publicKey,
  privateKey: privateKey,
  originalData: 'SM2 椭圆曲线公钥密码算法',
  encryptedData: '',
  decryptedData: ''
})

//加密
const encryptSM2 = () => {
  SM2Data.encryptedData = SM2.encrypt(SM2Data.originalData, SM2Data.publicKey, {
    inputEncoding: 'utf8',
    outputEncoding: 'base64'
  })
}

//解密
const decryptedSM2 = () => {
  SM2Data.decryptedData = SM2.decrypt(SM2Data.encryptedData, SM2Data.privateKey, {
    inputEncoding: 'base64',
    outputEncoding: 'utf8'
  })
}

4、SM3加密

let SM3Data = reactive({
  originalData: 'SM3水电费水电费',
  encryptedData: ''
})

//加密
const encryptSM3 = () => {
  // SM3Data.encryptedData = SM3.digest(SM3Data.originalData)
  // SM3Data.encryptedData = SM3.digest(SM3Data.originalData, 'base64')
  SM3Data.encryptedData = SM3.digest(SM3Data.originalData, 'utf8', 'base64')
}

5、SM4加密解密

let SM4Data = reactive({
  key: '0123456789abcdeffedcba9876543210',
  iv: '0123456789abcdeffedcba9876543210',
  originalData: 'SM4 国标对称加密',
  encryptedData: '',
  decryptedData: ''
})


//加密
const encryptSM4 = () => {
  // ECB
  SM4Data.encryptedData = SM4.encrypt(SM4Data.originalData, SM4Data.key, {
    inputEncoding: 'utf8',
    outputEncoding: 'base64'
  })
  //CBC
  // SM4Data.encryptedData = SM4.encrypt(SM4Data.originalData, SM4Data.key, {
  //   iv: SM4Data.iv,
  //   mode: SM2Data.constants.CBC,
  //   inputEncoding: 'utf8',
  //   outputEncoding: 'hex'
  // })
}
//解密
const decryptedSM4 = () => {
  // ECB
  SM4Data.decryptedData = SM4.decrypt(SM4Data.encryptedData, SM4Data.key, {
    inputEncoding: 'base64',
    outputEncoding: 'utf8'
  })
  //CBC
  // SM4Data.decryptedData = SM4.decrypt(SM4Data.encryptedData, SM4Data.key, {
  //   iv: SM4Data.iv,
  //   mode: SM2Data.constants.CBC,
  //   inputEncoding: 'utf8',
  //   outputEncoding: 'hex'
  // })
}

6、vue3+element完整代码




gm-crypto相关文档:https://gitcode.net/mirrors/byte-fe/gm-crypto?utm_source=csdn_github_accelerator

vue3+element ui例子:https://gitee.com/huanglgln/vue-sys-manage-el

 vue3+view ui例子:https://gitee.com/huanglgln/vue-sys-manage

 vue3+Ant Design Vue ui例子:https://gitee.com/huanglgln/vue-sys-manage-adv 

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