import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RSAEncryptUtil {
/**
* 公钥加密
*
* @param content 内容
* @param publicKey 公钥
* @return 加密后的密文
* @throws Exception 异常信息
*/
public static String encrypt(String content, String publicKey) throws Exception {
//base64编码的公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
return Base64.encodeBase64String(cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)));
}
/**
* 私钥解密
*
* @param content 内容
* @param privateKey 私钥
* @return 解密后的字符串
* @throws Exception 异常
*/
public static String decrypt(String content, String privateKey) throws Exception {
byte[] inputByte = Base64.decodeBase64(content.getBytes(StandardCharsets.UTF_8));
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
return new String(cipher.doFinal(inputByte));
}
/**
* 随机生成密钥对
*/
public static KeyPair genKeyPair() throws Exception {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(512, new SecureRandom());
return keyPairGen.generateKeyPair();
}
public static void main(String[] args) throws Exception {
KeyPair keyPair = genKeyPair();
RSAPrivateKey privateKeyRSA = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥
RSAPublicKey publicKeyRSA = (RSAPublicKey) keyPair.getPublic(); // 得到公钥
String publicKey = new String(Base64.encodeBase64(publicKeyRSA.getEncoded()));
// 得到私钥字符串
String privateKey = new String(Base64.encodeBase64((privateKeyRSA.getEncoded())));
String encrypt = encrypt("ldskjfsdlkjllkjlkj", publicKey);
System.out.println("加密密文:" + encrypt);
String decrypt = decrypt(encrypt, privateKey);
System.out.println("解密密文:" + decrypt);
}
}
RSA公私钥加密工具类
最新推荐文章于 2024-05-29 14:27:57 发布