• 【国密SM2】基于Hutool的SM2公私钥生成、签名验签(二十行代码搞定)


    前言

    由于在公司项目中需要用到国密SM2秘钥生成、签名、验签功能,找了网上很多的资料,发现其工具类都异常复杂,最终找到了Hutool工具包,但其官网的示例也不尽人意。于是,对Hutool提供的SM2类进行封装,封装成了自己使用的Sm2Util工具类,代码量在20行以内,尽可能做到简单易懂易用。

    实现

    1 引入hutool依赖

    <dependency>
      <groupId>cn.hutoolgroupId>
      <artifactId>hutool-allartifactId>
      <version>5.8.18version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    注意,这里的版本需使用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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    原因:在5.5.9修复了该问题,https://gitee.com/dromara/hutool/blob/v5-master/CHANGELOG_5.0-5.7.md

    image-20231009233538308

    2. Sm2Util工具类

    /**
     * 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));
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91

    测试

    签名验签测试

    /**
     * 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));
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    执行结果:

    公钥:048421649b6acdd22bc5075ef937dd35bb165b1db32eb4bd2fc666f07808819c88ac7dbeaeeb367bfe53601db55372bc16bf284dbf12f6b5f0df111023df88a4b0
    私钥:24382886faa9bf81d88e498179ac4edb7dac174b41bb41903841daecae4d996d
    签名值:304502201477495f51208c1df241c5e4b702f571bf2d963b921d284f073262936236948f022100b7192a75aea143903ee909283158e7e9ee76030010beea56c3626c508699b885
    正确的验签结果:true
    内容改变,验签结果:false
    公钥错误,验签结果:false
    错误签名,验签结果:false
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    加密解密测试

      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);
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    运行结果

    加密后结果:BKskZerb8k3COagR4kvUU9Lys/NUn57P4OzdBnve9p91LV+CpCjG1kG3Txo0lfo0r4oSB4b+Vvh56+lE/99l8I9zpPG99N+Fjf57GYnoTn1XtePn0oDE3GvhMen5RY7/Z/6FOoNWQAigaQ==
    解密后结果:hello SM2
    
    • 1
    • 2

    说明

    公私钥说明

    私钥的长度为64

    公钥的长度为130位,其中前两位为标识为,后面的128位为椭圆曲线上的x坐标和y坐标。
    公钥前缀为“04”时,表示未压缩公钥。

    其中,可以通过私钥算出对应的公钥,所以私钥一定要保护好!!!

    例如,可以通过以下网址进行计算,计算出的公钥需在前面补“04”

    通过SM2私钥计算SM2公钥网址

    参考文章:
    hutool官方文档

  • 相关阅读:
    平安校园智慧安防监控摄像头的布控建议
    3D包容盒子
    做接口测试的目的以及测试点
    【评论送书】十本架构师成长和软件架构技术相关的好书(可以任选)
    docker部署Vaultwarden密码共享管理系统
    zblog主题模板:zblog产品企业主题aymeighteen
    Springboot中使用kafka
    08 集群参数配置(下)
    CentOS 7.9检测硬盘坏区、实物定位(三)
    一、K8s中的一些重要概念和常用指令
  • 原文地址:https://blog.csdn.net/weixin_43811294/article/details/133758967