You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
74 lines
2.2 KiB
74 lines
2.2 KiB
import { SM4 } from "gm-crypto-wasm";
|
|
import * as CryptoJS from 'crypto-js'
|
|
/**
|
|
@ 作者: 秦东
|
|
@ 时间: 2025-12-07 10:26:51
|
|
@ 备注: 将字符串转换成16进制
|
|
*/
|
|
const strToHexMethod = (str: string): string => {
|
|
return CryptoJS.enc.Utf8.parse(str).toString(CryptoJS.enc.Hex)
|
|
}
|
|
/**
|
|
@ 作者: 秦东
|
|
@ 时间: 2025-12-07 10:29:48
|
|
@ 备注: 判断是不是12位16进制参数
|
|
*/
|
|
const isValidHex32 = (str: string): boolean => {
|
|
return /^[0-9a-fA-F]{32}$/.test(str)
|
|
}
|
|
/**
|
|
@ 作者: 秦东
|
|
@ 时间: 2025-12-07 10:28:33
|
|
@ 备注: 初始化SM4密钥参数
|
|
*/
|
|
const appSystemKey = strToHexMethod(import.meta.env.VITE_APP_SYSTEM_KEY)
|
|
const sm4TokenKey = strToHexMethod(import.meta.env.VITE_APP_SM4_APP_KEY)
|
|
|
|
/**
|
|
@ 作者: 秦东
|
|
@ 时间: 2026-02-11 08:17:36
|
|
@ 功能: SM4加密方法
|
|
*/
|
|
const sm4EncryptMethod = (data: string, customKey: string): string => {
|
|
let ivSetup = sm4TokenKey
|
|
if (customKey) {
|
|
ivSetup = strToHexMethod(customKey)
|
|
if (!isValidHex32(ivSetup)) {
|
|
ivSetup = sm4TokenKey
|
|
}
|
|
}
|
|
return SM4.encrypt(data, appSystemKey, {
|
|
iv: ivSetup,
|
|
mode: SM4.constants.CBC,
|
|
inputEncoding: 'utf8',
|
|
outputEncoding: 'hex',
|
|
padding: 1
|
|
} as never)
|
|
}
|
|
/**
|
|
@ 作者: 秦东
|
|
@ 时间: 2025-12-07 10:31:22
|
|
@ 备注: SM4解密方法
|
|
*/
|
|
const sm4DecryptMethod = (data: string, customKey: string): string => {
|
|
let ivSetup = sm4TokenKey
|
|
if (customKey) {
|
|
ivSetup = strToHexMethod(customKey)
|
|
if (!isValidHex32(ivSetup)) {
|
|
ivSetup = sm4TokenKey
|
|
}
|
|
}
|
|
// console.log('SM4解密方法----解密结构---data--->', data)
|
|
// console.log('SM4解密方法----解密结构----customKey-->', customKey)
|
|
// console.log('SM4解密方法----解密结构--ivSetup---->', ivSetup)
|
|
// console.log('SM4解密方法----解密结构---sm4TokenKey--->', sm4TokenKey)
|
|
// console.log('SM4解密方法----解密结构---appSystemKey--->', appSystemKey)
|
|
return SM4.decrypt(data, appSystemKey, {
|
|
iv: ivSetup,
|
|
mode: SM4.constants.CBC,
|
|
inputEncoding: 'hex',
|
|
outputEncoding: 'utf8',
|
|
padding: 1
|
|
} as never)
|
|
}
|
|
export { sm4EncryptMethod, sm4DecryptMethod }
|
|
|