import java.nio.charset.StandardCharsets;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import cn.hutool.crypto.BCUtil;
import cn.hutool.crypto.ECKeyUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
public class SM2Util {
/**
* 生成密钥对
* @return
*/
public static SM2KeyPair generateKeyPair() {
SM2 sm2 = SmUtil.sm2();
//这里会自动生成对应的随机秘钥对 , 注意! 这里一定要强转,才能得到对应有效的秘钥信息
byte[] privateKey = BCUtil.encodeECPrivateKey(sm2.getPrivateKey());
//这里公钥不压缩 公钥的第一个字节用于表示是否压缩 可以不要
byte[] publicKey = ((BCECPublicKey) sm2.getPublicKey()).getQ().getEncoded(false);
SM2KeyPair sm2KeyPair = new SM2KeyPair();
sm2KeyPair.setPrivateKey(Util.byteToHex(privateKey));
sm2KeyPair.setPublicKey(Util.byteToHex(publicKey));
return sm2KeyPair;
}
/**
* 加密
* @param publicKey
* @param mode
* @param text
* @return byte2Hex
*/
public static String encrypt(String publicKey, SM2Engine.Mode mode, String text) {
SM2 sm2 = SmUtil.sm2();
sm2.setPublicKeyParams(ECKeyUtil.toSm2PublicParams(publicKey));
sm2.setMode(mode);
byte[] encrypt = sm2.encrypt(text.getBytes(StandardCharsets.UTF_8), KeyType.PublicKey);
return Util.byteToHex(encrypt);
}
/**
* 解密
* @param privateKey
* @param mode SM2Engine.Mode
* @param text hexString
* @return
*/
public static String decrypt(String privateKey, SM2Engine.Mode mode, String text) {
SM2 sm2 = SmUtil.sm2();
sm2.setPrivateKeyParams(ECKeyUtil.toSm2PrivateParams(privateKey));
sm2.setMode(mode);
byte[] encrypt = sm2.decrypt(Util.hexToByte(text), KeyType.PrivateKey);
return new String(encrypt);
}
}