{
"channelId": 2376543,
"pageNumber": 1,
"pageSize": 10
}
SM2Util.encrypt(respEncryptKey, SM2Engine.Mode.C1C2C3, xparam)
http://api.polyv.net/xxx?appId=xxx&sign=xxx×tamp=xxx&xparam=ABCDEF
{
"code": 400,
"status": "error",
"error": {
"code": 10001,
"desc": "参数错误"
},
"success": false
}
{
"code": 200,
"status": "success",
"data": "043D1BF16CB1C2629348A7B18F9C51036C9466F3E198F75C6ABDE83A428E2893",
"success": true
}
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.2</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.70</version>
</dependency>
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);
}
}