官方参考文档:https://hutool.cn/docs/#/crypto/非对称加密-AsymmetricCrypto
一、生成密钥对
@Test
void createRsa() {
// 初始化RSA工具,生成密钥对
RSA rsa = new RSA();
// 获取公钥
String pubKey = rsa.getPublicKeyBase64();
System.out.println("pubKey:" + pubKey);
// 获取私钥
String priKey = rsa.getPrivateKeyBase64();
System.out.println("priKey:" + priKey);
}
二、加解密用例
一般使用时,一个方法只会用到一个密钥,公钥加密私钥解密,或私钥加密公钥解密。
@Test
void rsa() {
String data = "这是一个小例子haha";
String pubKey = "xxxxx";
String priKey = "xxxxx";
// 初始化RSA工具并设置私钥
RSA priRsa = new RSA(priKey, null);
// 初始化RSA工具并设置公钥
RSA pubRsa = new RSA(null, pubKey);
// 初始化自定义密钥对RSA工具,但是一般不这么用,因为公私钥需要分离
RSA Rsa = new RSA(priKey, pubKey);
// 公钥加密
String encodeStr = pubRsa.encryptBase64(data, KeyType.PublicKey);
System.out.println("encodeStr by public key:" + encodeStr);
// 私钥解密
String decodeStr = priRsa.decryptStr(encodeStr, KeyType.PrivateKey);
System.out.println("decodeStr by private key:" + decodeStr);
// 私钥加密
String encodeStr1 = priRsa.encryptBase64(data, KeyType.PrivateKey);
System.out.println("encodeStr1 by private key:" + encodeStr1);
// 公钥解密
String decodeStr1 = pubRsa.decryptStr(encodeStr1, KeyType.PublicKey);
System.out.println("decodeStr1 by public key:" + decodeStr1);
}
三、总结
@Test
void hutoolRSA() {
RSA rsa = new RSA();
String publicKeyStr = rsa.getPublicKeyBase64();
System.out.println(String.format(" 公钥Base64字符串:%s\n", publicKeyStr));
String privateKeyStr = rsa.getPrivateKeyBase64();
System.out.println(String.format(" 私钥Base64字符串:%s\n", privateKeyStr));
RSA publicKey = new RSA(null, publicKeyStr);
String encryptAfterStr = publicKey.encryptBase64(StrUtil.str("Luv your smile.", CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey);
System.out.println(String.format("加密后Base64字符串:%s\n", encryptAfterStr));
RSA privateKey = new RSA(privateKeyStr, null);
String decryptAfterStr = privateKey.decryptStr(encryptAfterStr, KeyType.PrivateKey);
System.out.println(String.format(" 解密后字符串:%s\n", decryptAfterStr));
}
评论区