SM4 is a block cipher algorithm. It supports multiple modes of operation, including:
ECB: Electronic CodebookCBC: Cipher Block Chaining
To use CBC mode, you must provide an iv (Initialization Vector). The key should be a string of 32 hexadecimal digits. You can specify inputEncoding, outputEncoding, mode, and iv in the options object.
const { SM4 } = require('gm-crypto')
const key = '0123456789abcdeffedcba9876543210' // Any string of 32 hexadecimal digits
const originalData = 'SM4 国标对称加密'
let encryptedData, decryptedData
// ECB mode
encryptedData = SM4.encrypt(originalData, key, {
inputEncoding: 'utf8',
outputEncoding: 'base64'
})
decryptedData = SM4.decrypt(encryptedData, key, {
inputEncoding: 'base64',
outputEncoding: 'utf8'
})
// CBC mode
const iv = '0123456789abcdeffedcba9876543210' // Initialization vector (32 hex 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'
})