1.导入hutool依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.18</version>
</dependency>
2.直接复制代码
package com.common.utils;
import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.AsymmetricAlgorithm;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import java.security.KeyPair;
import java.util.LinkedList;
/**
* 非对称加密工具类
*
* @author edimen
*/
public class AsymmetricAlgorithmUtil {
/**
* 公钥加密(解密就要用到对应的私钥)
*
* @param msg 明文信息
* @param pubKey 公钥,用来加密明文
* @return
*/
public static String encryptByPublic(String msg, String pubKey) {
RSA rsa = new RSA(AsymmetricAlgorithm.RSA_ECB_PKCS1.getValue(), null, pubKey);
return rsa.encryptBase64(msg, KeyType.PublicKey);
}
/**
* 私钥解密
*
* @param encryptMsg 公钥加密的密文
* @param priKey 私钥,用来解密密文
* @return
*/
public static String decryptByPrivate(String encryptMsg, String priKey) {
RSA rsa = new RSA(AsymmetricAlgorithm.RSA_ECB_PKCS1.getValue(), priKey, null);
return rsa.decryptStr(encryptMsg, KeyType.PrivateKey);
}
/**
* 私钥加密(解密就要用到对应的公钥)
*
* @param msg 明文信息
* @param priKey 私钥,用来加密明文
* @return
*/
public static String encryptByPrivate(String msg, String priKey) {
RSA rsa = new RSA(AsymmetricAlgorithm.RSA_ECB_PKCS1.getValue(), priKey, null);
return rsa.encryptBase64(msg, KeyType.PrivateKey);
}
/**
* 公钥解密
*
* @param encryptMsg 密文
* @param pubKey 公钥,用来解密
* @return
*/
public static String decryptByPublic(String encryptMsg, String pubKey) {
RSA rsa = new RSA(AsymmetricAlgorithm.RSA_ECB_PKCS1.getValue(), null, pubKey);
return rsa.decryptStr(encryptMsg, KeyType.PublicKey);
}
/**
* 获取公私钥集合
*
* @return
*/
public static LinkedList<String> getPriKeyAndPubKey() {
KeyPair pair = SecureUtil.generateKeyPair("RSA");
String privateKey = Base64.encode(pair.getPrivate().getEncoded());
String publicKey = Base64.encode(pair.getPublic().getEncoded());
LinkedList<String> keys = new LinkedList<>();
keys.add(privateKey);
keys.add(publicKey);
return keys;
}
}
3.测试案例
public static void main(String[] args) {
LinkedList<String> priKeyAndPubKey = AsymmetricAlgorithmUtil.getPriKeyAndPubKey();
String privateKey = priKeyAndPubKey.get(0);
String publicKey = priKeyAndPubKey.get(1);
String text = "HelloWorld";
String encryptByPublic = AsymmetricAlgorithmUtil.encryptByPublic(text, publicKey);
System.out.println(encryptByPublic);
String s = AsymmetricAlgorithmUtil.decryptByPrivate(encryptByPublic, privateKey);
System.out.println("公钥加密私钥解密:"+s);
String encryptByPrivate = AsymmetricAlgorithmUtil.encryptByPrivate(text, privateKey);
System.out.println(encryptByPrivate);
String s1 = AsymmetricAlgorithmUtil.decryptByPublic(encryptByPrivate,publicKey);
System.out.println("私钥加密公钥解密:"+s1);
}
4.运行结果图: