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

master
dap 4 months ago
parent 450e70704b
commit 4f8a7c0524

@ -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);
/**
* sm2java.lang.IllegalArgumentException: Invalid point coordinates
* @see https://github.com/chinabugotech/hutool/issues/3262
*
* 04
*/
return '04' + sm2.doEncrypt(str, this.publicKey);
}
}

@ -7,10 +7,16 @@ import { BaseSymmetricEncryption } from '../base';
* SM4
*/
export class Sm4Encryption extends BaseSymmetricEncryption {
override decrypt(data: string, key: string): string {
/**
* datahex 使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 {

Loading…
Cancel
Save