RSA加密算法
RSA算法是一种非对称密码算法,所谓非对称,就是指该算法需要一对密钥,使用其中一个加密,则需要用另一个才能解密。例如:
(1)乙方生成两把密钥(公钥和私钥)。公钥是公开的,任何人都可以获得,私钥则是保密的。
(2)甲方获取乙方的公钥,然后用它对信息加密。
(3)乙方得到加密后的信息,用私钥解密
公钥加密的信息只有私钥解得开,那么只要私钥不泄漏,通信就是安全的。
工具类:
package org.springblade.winsun.utils;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
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();
//公钥
RSAPublicKey publicKeyRSA = (RSAPublicKey) keyPair.getPublic();
//私钥
RSAPrivateKey privateKeyRSA = (RSAPrivateKey) keyPair.getPrivate();
String publicKey = new String(Base64.encodeBase64(publicKeyRSA.getEncoded()));
// 得到私钥字符串
String privateKey = new String(Base64.encodeBase64((privateKeyRSA.getEncoded())));
System.out.println("公钥:"+publicKey);
System.out.println("私钥:"+privateKey);
String encrypt = encrypt("123", publicKey);
System.out.println("加密密文:" + encrypt);
String decrypt = decrypt(encrypt, privateKey);
System.out.println("解密密文:" + decrypt);
}
}