44 lines
1.6 KiB
Java
Raw Normal View History

package com.cdzy.common.secure;
import cn.hutool.crypto.BCUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import java.nio.charset.StandardCharsets;
/**
* SM2加解密组件
* @author 李洪贵
* @date 2025年03月17日 17:46
*/
public class SecureSM2Component implements SecureComponent {
@Override
public String encrypt(String originalText,String publicKey) {
try {
if (publicKey.length() == 130)
publicKey = publicKey.substring(2);
String xhex = publicKey.substring(0, 64);
String yhex = publicKey.substring(64, 128);
ECPublicKeyParameters ecPublicKeyParameters = BCUtil.toSm2Params(xhex, yhex);
cn.hutool.crypto.asymmetric.SM2 sm2 = new cn.hutool.crypto.asymmetric.SM2(null, ecPublicKeyParameters);
String encryptStr = sm2.encryptBcd(originalText, KeyType.PublicKey, StandardCharsets.UTF_8);
return encryptStr;
} catch (Exception e) {
return null;
}
}
@Override
public String decrypt(String encryptedText, String privateKey) {
try {
ECPrivateKeyParameters privateKeyParameters = BCUtil.toSm2Params(privateKey);
cn.hutool.crypto.asymmetric.SM2 sm2 = new cn.hutool.crypto.asymmetric.SM2(privateKeyParameters, null);
String decryptStr = sm2.decryptStrFromBcd(encryptedText, KeyType.PrivateKey, StandardCharsets.UTF_8);
return decryptStr;
} catch (Exception e) {
return null;
}
}
}