package com.hejjon.encryptdemo;
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
/**
* 封装RSA加密工具类
* @author: cs
* @date: 2023-02-16 13:34:36
* @since: 1.0
*/
public class RSAUtil {
private static final String RSA = "RSA";
private static String rsaPublicKey = null;
private static String rsaPrivateKey = null;
/**
* //构建密钥对,保存公私钥
*
* @throws NoSuchAlgorithmException
*/
static {
try {
KeyPairGenerator rsa = KeyPairGenerator.getInstance(RSA);
rsa.initialize(512);
KeyPair keyPair = rsa.generateKeyPair();
// 生成公钥
RSAPublicKey rsaPublic = (RSAPublicKey) keyPair.getPublic();
// 生成私钥
RSAPrivateKey rsaPrivate = (RSAPrivateKey) keyPair.getPrivate();
// 生成公钥字符串
rsaPublicKey = Base64.getEncoder().encodeToString(rsaPublic.getEncoded());
// 生成私钥字符串
rsaPrivateKey = Base64.getEncoder().encodeToString(rsaPrivate.getEncoded());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 私钥加密
* @return
* @throws Exception
*/
public static String encByPrivateKey(String content) throws Exception {
if (content == null || "".equals(content)) {
throw new Exception("content is null or empty!");
}
System.out.println("要加密的数据: " + content);
// 在构建密钥对时对秘钥进行了base64 编码, 这里需要先解码
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(rsaPrivateKey));
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
// 创建Cipher对象
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
// 加密
byte[] bytes = cipher.doFinal(content.getBytes());
String result = Base64.getEncoder().encodeToString(bytes);
System.out.println("私钥加密的结果: " + result);
return result;
}
/**
* 公钥解密
*
* @param
* @param result 加密的数据
* @return
*/
public static String decByPublicKey(String result) throws Exception {
// 先对公钥进行Base64 解码
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(rsaPublicKey));
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
// 创建Cipher对象
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(result));
String content = new String(bytes);
System.out.println("公钥解密的结果: " + content);
return content;
}
}