一、算法介绍
RSA是非对称加密算法,这种加密算法有两个密钥,一个用来加密数据,一个用来解密数据。
二、功能实现
代码实现及使用案例如下:
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.Cipher;
/**
* RSA加密工具类
* @since 2023-09-14 10:33
*
*/
public class RSAUtil {
private static final String RSA = "RSA";
/**
* 生成密钥
* @return
* @throws NoSuchAlgorithmException
*/
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA);
keyPairGenerator.initialize(2048, new SecureRandom());
return keyPairGenerator.genKeyPair();
}
/**
* 加密
* @param plainText 明文
* @param publicKey 公钥
* @return 加密后的密文
* @throws Exception
*/
public static String encrypt(String plainText, PublicKey publicKey) throws Exception {
return Base64.getEncoder().encodeToString(encrypt(plainText.getBytes(), publicKey));
}
/**
* 加密
* @param data 明文二级制数组
* @param publicKey 公钥
* @return 加密后的密文二级制数组
* @throws Exception
*/
public static byte[] encrypt(byte[] data, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
}
/**
* 解密
* @param encryptedData 密文
* @param privateKey 私钥
* @return 解密后的明文
* @throws Exception
*/
public static String decrypt(String encryptedData, PrivateKey privateKey) throws Exception {
return new String(decrypt(Base64.getDecoder().decode(encryptedData), privateKey), StandardCharsets.UTF_8);
}
/**
* 解密
* @param encryptedData 密文的二进制数组
* @param privateKey 私钥
* @return 解密后明文的二进制数组
* @throws Exception
*/
public static byte[] decrypt(byte[] encryptedData, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(encryptedData);
}
public static void main(String[] args) throws Exception {
// 生成RSA密钥对
KeyPair keyPair = generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// 明文
String plainText = "hello world!";
//加密
String c = encrypt(plainText, publicKey);
System.out.println(c);
//解密
System.out.println(decrypt(c, privateKey));
}
}
如果对你有用的话,记得点赞加关注😊