关于SM4加解密的记录

开头:最近对接的项目要求对用户信息进行SM4加秘传递,所以了解了一下使用方法

1,使用方式

安装依赖:npm i gm-crypto

2,使用

 

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' }
)

官方文档:gm-crypto - npm

 

posted @ 2024-12-24 10:28  白夜初晓  阅读(272)  评论(0)    收藏  举报