由于在公司项目中需要用到国密SM2秘钥生成、签名、验签功能,找了网上很多的资料,发现其工具类都异常复杂,最终找到了Hutool
工具包,但其官网的示例也不尽人意。于是,对Hutool
提供的SM2类进行封装,封装成了自己使用的Sm2Util
工具类,代码量在20行以内,尽可能做到简单易懂易用。
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-allartifactId>
<version>5.8.18version>
dependency>
注意,这里的版本需使用
5.5.9
及以上版本,否则就会报以下错误
Exception in thread "main" cn.hutool.crypto.CryptoException: InvalidKeySpecException: encoded key spec not recognized: failed to construct sequence from byte[]: DER length more than 4 bytes: 76
at cn.hutool.crypto.KeyUtil.generatePrivateKey(KeyUtil.java:287)
at cn.hutool.crypto.KeyUtil.generatePrivateKey(KeyUtil.java:267)
at cn.hutool.crypto.asymmetric.SM2.<init>(SM2.java:82)
at cn.hutool.crypto.asymmetric.SM2.<init>(SM2.java:69)
at xyz.lys.job.Sm2Util.sign(Sm2Util.java:54)
at xyz.lys.job.Sm2UtilTest.main(Sm2UtilTest.java:26)
原因:在5.5.9
修复了该问题,https://gitee.com/dromara/hutool/blob/v5-master/CHANGELOG_5.0-5.7.md
/**
* SM2秘钥生成、签名、验签工具类
* @author 只有影子
*/
public class Sm2Util {
/**
* 公钥常量
*/
public static final String KEY_PUBLIC_KEY = "publicKey";
/**
* 私钥返回值常量
*/
public static final String KEY_PRIVATE_KEY = "privateKey";
/**
* 生成SM2公私钥
*
* @return
*/
public static Map<String, String> generateSm2Key() {
SM2 sm2 = new SM2();
ECPublicKey publicKey = (ECPublicKey) sm2.getPublicKey();
ECPrivateKey privateKey = (ECPrivateKey) sm2.getPrivateKey();
// 获取公钥
byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
String publicKeyHex = HexUtil.encodeHexStr(publicKeyBytes);
// 获取64位私钥
String privateKeyHex = privateKey.getD().toString(16);
// BigInteger转成16进制时,不一定长度为64,如果私钥长度小于64,则在前方补0
StringBuilder privateKey64 = new StringBuilder(privateKeyHex);
while (privateKey64.length() < 64) {
privateKey64.insert(0, "0");
}
Map<String, String> result = new HashMap<>();
result.put(KEY_PUBLIC_KEY, publicKeyHex);
result.put(KEY_PRIVATE_KEY, privateKey64.toString());
return result;
}
/**
* SM2私钥签名
*
* @param privateKey 私钥
* @param content 待签名内容
* @return 签名值
*/
public static String sign(String privateKey, String content) {
SM2 sm2 = new SM2(privateKey, null);
return sm2.signHex(HexUtil.encodeHexStr(content));
}
/**
* SM2公钥验签
*
* @param publicKey 公钥
* @param content 原始内容
* @param sign 签名
* @return 验签结果
*/
public static boolean verify(String publicKey, String content, String sign) {
SM2 sm2 = new SM2(null, publicKey);
return sm2.verifyHex(HexUtil.encodeHexStr(content), sign);
}
/**
* SM2公钥加密
*
* @param content 原文
* @param publicKey SM2公钥
* @return
*/
public static String encryptBase64(String content, String publicKey) {
SM2 sm2 = new SM2(null, publicKey);
return sm2.encryptBase64(content, KeyType.PublicKey);
}
/**
* SM2私钥解密
*
* @param encryptStr SM2加密字符串
* @param privateKey SM2私钥
* @return
*/
public static String decryptBase64(String encryptStr, String privateKey) {
SM2 sm2 = new SM2(privateKey, null);
return StrUtil.utf8Str(sm2.decrypt(encryptStr, KeyType.PrivateKey));
}
}
/**
* SM2工具类对应测试类
*/
public class Sm2UtilTest {
public static void main(String[] args) {
// 生成SM2秘钥
Map<String, String> smKeyMap = Sm2Util.generateSm2Key();
String publicKey = smKeyMap.get(Sm2Util.KEY_PUBLIC_KEY);
String privateKey = smKeyMap.get(Sm2Util.KEY_PRIVATE_KEY);
System.out.println("公钥:" + publicKey);
System.out.println("私钥:" + privateKey);
String testStr = "hello";
// 使用私钥SM2签名
String sign = Sm2Util.sign(privateKey, testStr);
System.out.println("签名值:" + sign);
// 私钥公钥验签成功例子
boolean verify = Sm2Util.verify(publicKey, testStr, sign);
System.out.println("正确的验签结果:" + verify);
// 私钥公钥验签失败例子
System.out.println("内容改变,验签结果:" + Sm2Util.verify(publicKey, "error", sign));
System.out.println("公钥错误,验签结果:" + Sm2Util.verify(Sm2Util.generateSm2Key().get(Sm2Util.KEY_PUBLIC_KEY), testStr, sign));
String errorSign = "3046022100e39b3937056d9652c10d3aa8a850b8b4075ec7c0adea60af26e4865121d400ad022100d41295331c29e14bd5e70f7325a3d9ac1716662cc766db710323dac873d62ab0";
System.out.println("错误签名,验签结果:" + Sm2Util.verify(publicKey, testStr, errorSign));
}
}
执行结果:
公钥:048421649b6acdd22bc5075ef937dd35bb165b1db32eb4bd2fc666f07808819c88ac7dbeaeeb367bfe53601db55372bc16bf284dbf12f6b5f0df111023df88a4b0
私钥:24382886faa9bf81d88e498179ac4edb7dac174b41bb41903841daecae4d996d
签名值:304502201477495f51208c1df241c5e4b702f571bf2d963b921d284f073262936236948f022100b7192a75aea143903ee909283158e7e9ee76030010beea56c3626c508699b885
正确的验签结果:true
内容改变,验签结果:false
公钥错误,验签结果:false
错误签名,验签结果:false
public static void main(String[] args) {
String privateKey = "24382886faa9bf81d88e498179ac4edb7dac174b41bb41903841daecae4d996d";
String publicKey = "048421649b6acdd22bc5075ef937dd35bb165b1db32eb4bd2fc666f07808819c88ac7dbeaeeb367bfe53601db55372bc16bf284dbf12f6b5f0df111023df88a4b0";
String str = "hello SM2";
String encrypt = encryptBase64(str, publicKey);
System.out.println("加密后结果:" + encrypt);
String decrypt = decryptBase64(encrypt, privateKey);
System.out.println("解密后结果:" + decrypt);
Assert.assertEquals(str, decrypt);
}
运行结果
加密后结果:BKskZerb8k3COagR4kvUU9Lys/NUn57P4OzdBnve9p91LV+CpCjG1kG3Txo0lfo0r4oSB4b+Vvh56+lE/99l8I9zpPG99N+Fjf57GYnoTn1XtePn0oDE3GvhMen5RY7/Z/6FOoNWQAigaQ==
解密后结果:hello SM2
私钥的长度为64位
公钥的长度为130位,其中前两位为标识为,后面的128位为椭圆曲线上的x坐标和y坐标。
公钥前缀为“04”时,表示未压缩公钥。
其中,可以通过私钥算出对应的公钥,所以私钥一定要保护好!!!
例如,可以通过以下网址进行计算,计算出的公钥需在前面补“04”
参考文章:
hutool官方文档