vue+gm-crypto 国密SM4、SM3、SM2加密和解密

2021-11-19  本文已影响0人  张xiao蛋

一、首先 下载gm-crypto插件

npm install gm-crypto
//或者
yarn add gm-crypto

二、页面直接引入gm-crypto

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

SM2

const { publicKey, privateKey } = SM2.generateKeyPair()
const originalData = 'SM2 椭圆曲线公钥密码算法'

const encryptedData = SM2.encrypt(originalData, publicKey, {
  inputEncoding: 'utf8',
  outputEncoding: 'base64'
})

const decryptedData = SM2.decrypt(encryptedData, privateKey, {
  inputEncoding: 'base64',
  outputEncoding: 'utf8'
})

SM3

console.log(SM3.digest('abc'))
console.log(SM3.digest('YWJj', 'base64'))
console.log(SM3.digest('616263', 'hex', 'base64'))

SM4

const key = '0123456789abcdeffedcba9876543210' // Any string of 32 hexadecimal digits
const originalData = 'SM4 国标对称加密'

/**
 * Block cipher modes:
 * - ECB: electronic codebook
 * - CBC: cipher block chaining
 */

let encryptedData, decryptedData

// ECB
encryptedData = SM4.encrypt(originalData, key, {
  inputEncoding: 'utf8',
  outputEncoding: 'base64'
})
decryptedData = SM4.decrypt(encryptedData, key, {
  inputEncoding: 'base64',
  outputEncoding: 'utf8'
})

// CBC
const iv = '0123456789abcdeffedcba9876543210' // Initialization vector(any string of 32 hexadecimal digits)实在不会写就直接用32个0代替
encryptedData = SM4.encrypt(originalData, key, {
  iv,
  mode: SM2.constants.CBC,
  inputEncoding: 'utf8',
  outputEncoding: 'hex'
})
decryptedData = SM4.decrypt(encryptedData, key, {
  iv,
  mode: SM2.constants.CBC,
  inputEncoding: 'hex',
  outputEncoding: 'utf8'
})

gm-crypto的api详见https://gitcode.net/mirrors/byte-fe/gm-crypto?utm_source=csdn_github_accelerator

上一篇下一篇

猜你喜欢

热点阅读