关于hutool工具箱进行RSA非对称加密的使用笔记
首先是导入hutool工具包的maven依赖
<!-- huTool工具箱 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.22</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15to18</artifactId>
<version>1.69</version>
</dependency>
然后是 生成密钥对(只生成需要一次)
接着是使用私钥加密公钥解密或者公钥加密私钥解密(根据需求)
@Test public void rsa(){ String text = "123"; //生成公私钥对 KeyPair pair = SecureUtil.generateKeyPair("RSA"); PrivateKey privateKey = pair.getPrivate(); PublicKey publicKey = pair.getPublic(); //获得私钥 String privateKeyStr = bytesToBase64(privateKey.getEncoded()); System.out.println("私钥:" + privateKeyStr); //获得公钥 String publicKeyStr = bytesToBase64(publicKey.getEncoded()); System.out.println("公钥:" + publicKeyStr); RSA rsa = new RSA(privateKeyStr, publicKeyStr); System.out.println(rsa); //公钥加密,私钥解密 byte[] encrypt = rsa.encrypt(StrUtil.bytes(text, CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey); System.out.println("公钥加密:" + bytesToBase64(encrypt)); byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey);
//解密的同时把解密的结果转换成String字符串输出 System.out.println("私钥解密:" + new String(decrypt,StandardCharsets.UTF_8));
}
借鉴了大佬的文章,这里只是做个笔记需要的可以看大佬的文章 https://www.cnblogs.com/hdwang/p/16310314.html

浙公网安备 33010602011771号