vue项目中使用sm4加密 ,gm-crypto

参考地址

https://www.npmjs.com/package/gm-crypto

 

安装插件命令

npm i gm-crypto

 

使用

import {SM4} from "gm-crypto"

 

const key="xxxxx324324前后端统一的key"

const text="需要加密的文本"

const sm4Text= SM4.encrypt(text, key); //加密后的信息
 
const sm4EText=SM4.decrypt(sm4Text, key);//解密后的文本
 
 
官方例子
const { SM4 } = require('gm-crypto')

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)
encryptedData = SM4.encrypt(originalData, key, {
  iv: iv,
  mode: SM4.constants.CBC,
  inputEncoding: 'utf8',
  outputEncoding: 'hex'
})
decryptedData = SM4.decrypt(encryptedData, key, {
  iv: iv,
  mode: SM4.constants.CBC,
  inputEncoding: 'hex',
  outputEncoding: 'utf8'
})

 

 

posted @ 2025-11-05 11:52  山吹同学  阅读(8)  评论(0)    收藏  举报