bonus-ui/src/utils/sm.js

51 lines
1.4 KiB
JavaScript
Raw Normal View History

2024-07-24 10:51:57 +08:00
// src/utils/encryption.js
2024-09-13 16:06:50 +08:00
import { sm2, sm3, sm4 } from 'sm-crypto'
// 配置项例如盐值、SM2 公私钥、SM4 密钥
2024-08-06 15:47:19 +08:00
import { SM_CONFIG } from './configure'
2024-11-06 10:05:50 +08:00
import SM4 from 'sm-crypto/src/sm4'
import { hexToArray } from 'sm-crypto/src/sm2/utils'
2024-09-13 16:06:50 +08:00
2024-07-24 10:51:57 +08:00
// SM3 哈希
2024-08-06 15:47:19 +08:00
export function hashSM3(text) {
2024-07-24 10:51:57 +08:00
// 对数据进行哈希计算
2024-08-06 15:47:19 +08:00
return sm3(text)
2024-07-24 10:51:57 +08:00
}
// 使用 SM3 进行哈希并加入盐值
export function hashWithSM3AndSalt(text) {
// 将文本和盐值拼接在一起
2024-08-06 15:47:19 +08:00
const textWithSalt = SM_CONFIG.SALT + text
2024-07-24 10:51:57 +08:00
// 使用 SM3 进行哈希
2024-08-06 15:47:19 +08:00
return hashSM3(textWithSalt)
2024-07-24 10:51:57 +08:00
}
2024-09-13 16:06:50 +08:00
// SM2 加密
export function encryptWithSM2(text) {
// SM2 公钥加密
return sm2.doEncrypt(text, SM_CONFIG.SM2_PUBLIC_KEY)
}
// SM2 解密
export function decryptWithSM2(encryptedText) {
// SM2 私钥解密
return sm2.doDecrypt(encryptedText, SM_CONFIG.SM2_PRIVATE_KEY)
}
2024-11-06 10:05:50 +08:00
/**
* 加密函数
* @param {string} plainText
* @returns {string} 加密后的密文Hex 编码格式
*/
export function encryptWithSM4(plainText) {
2024-11-08 15:01:17 +08:00
return sm4.encrypt(plainText, SM_CONFIG.SM4_KEY,{ mode: 'cbc', padding: 'pkcs#5',iv:SM_CONFIG.SM4_SALT});
2024-09-13 16:06:50 +08:00
}
2024-11-06 10:05:50 +08:00
/**
* 解密函数
* @param {string} cipherText
* @returns {string} 解密后的明文
*/
export function decryptWithSM4(cipherText){
2024-11-08 15:01:17 +08:00
return SM4.decrypt(cipherText, SM_CONFIG.SM4_KEY,{ mode: 'cbc', padding: 'pkcs#5' ,iv:SM_CONFIG.SM4_SALT});
2024-09-13 16:06:50 +08:00
}
2024-11-06 10:05:50 +08:00