refactor: sm4/sm2加解密逻辑优化

This commit is contained in:
dap
2025-08-23 18:36:02 +08:00
parent 450e70704b
commit 4f8a7c0524
2 changed files with 28 additions and 5 deletions

View File

@@ -1,3 +1,4 @@
/* eslint-disable prefer-template */
/* eslint-disable no-console */
import { sm2 } from 'sm-crypto';
@@ -9,12 +10,28 @@ import { BaseAsymmetricEncryption } from '../base';
* @see https://tool.hiofd.com/sm2-key-gen/ 这里可以生成04开头的SM2密钥对
*/
export class Sm2Encryption extends BaseAsymmetricEncryption {
override decrypt(str: string): string {
return sm2.doDecrypt(str, this.privateKey);
override decrypt(hexStr: string): string {
/**
* 后端必须使用`EncryptUtils.encryptBySm2Hex`来加密而不是base64
* 后端返回会固定带04前缀 需要去除
*
* @see https://github.com/JuneAndGreen/sm-crypto?tab=readme-ov-file#%E5%8A%A0%E5%AF%86%E8%A7%A3%E5%AF%86
* ps密文会在解密时自动补充 04如遇到其他工具补充的 04 需手动去除再传入。
*/
if (hexStr.startsWith('04')) {
hexStr = hexStr.slice(2);
}
return sm2.doDecrypt(hexStr, this.privateKey);
}
override encrypt(str: string): string {
return sm2.doEncrypt(str, this.publicKey);
/**
* sm2解密有千分之几的错误报异常java.lang.IllegalArgumentException: Invalid point coordinates
* @see https://github.com/chinabugotech/hutool/issues/3262
*
* 固定加上04前缀 避免出现上述问题
*/
return '04' + sm2.doEncrypt(str, this.publicKey);
}
}

View File

@@ -7,10 +7,16 @@ import { BaseSymmetricEncryption } from '../base';
* SM4 实现
*/
export class Sm4Encryption extends BaseSymmetricEncryption {
override decrypt(data: string, key: string): string {
/**
* 解密 data必须为hex字符串 可使用后端EncryptUtils.encryptBySm4Hex来加密
* @param hexString 待解密数据 只接受hex类型的字符串
* @param key 秘钥
* @returns result
*/
override decrypt(hexString: string, key: string): string {
this.checkKey(key);
const keyHex = CryptoJS.enc.Hex.stringify(CryptoJS.enc.Utf8.parse(key));
return sm4.decrypt(data, keyHex);
return sm4.decrypt(hexString, keyHex);
}
override encrypt(data: string, key: string): string {