基于hutool实现国密SM2的加解密

2023-12-26 17:07:45

添加以下依赖

        <dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-all</artifactId>
			<version>5.8.16</version>
		</dependency>
		<!-- sm2加解密依赖 -->
		<dependency>
			<groupId>org.bouncycastle</groupId>
			<artifactId>bcprov-jdk15on</artifactId>
			<version>1.70</version>
		</dependency>

实现:

生成密钥对:

        //生成公钥对
        KeyPair pair = SecureUtil.generateKeyPair("SM2");
        //私钥
        String privateKeyStr = Base64.getEncoder().encodeToString(pair.getPrivate().getEncoded());
        //公钥
        String publicKeyStr =Base64.getEncoder().encodeToString(pair.getPublic().getEncoded());
        System.out.println("私钥 "+privateKeyStr);
        System.out.println("公钥 "+publicKeyStr);

加解密:

        //加密内容
        String content = "我是你大爷";

        //私钥签名
        SM2 sm2 = SmUtil.sm2(privateKeyStr,null);
        String sign = sm2.signHex(HexUtil.encodeHexStr(content));

        //公钥验签
         SM2 sm2PublicKeyStr = SmUtil.sm2(null,publicKeyStr);
        // true
        boolean verify = sm2PublicKeyStr.verifyHex(HexUtil.encodeHexStr(content), sign);

        //公钥加密
        // 公钥加密,私钥解密
        SM2 sm2publicKeyStr = SmUtil.sm2(null, publicKeyStr);
        String encryptStr = sm2publicKeyStr.encryptBcd(content, KeyType.PublicKey);

        //私钥解密
        SM2 sm2privateKeyStr = SmUtil.sm2(privateKeyStr, null);
        String decryptStr = StrUtil.utf8Str(sm2privateKeyStr.decryptFromBcd(encryptStr, KeyType.PrivateKey));




文章来源:https://blog.csdn.net/qq_35893120/article/details/135223338
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。