以下是使用Java 8实现RSA非对称加密的完整代码示例,包括密钥生成、加密和解密过程。
1. 生成RSA密钥对
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
public class RSAEncryptionExample {
public static void main(String[] args) throws Exception {
// 生成RSA密钥对
KeyPair keyPair = generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 将密钥转换为字符串形式(便于存储和传输)
String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded());
String privateKeyString = Base64.getEncoder().encodeToString(privateKey.getEncoded());
System.out.println("公钥: " + publicKeyString);
System.out.println("私钥: " + privateKeyString);
// 原始数据
String originalData = "这是一段需要加密的敏感数据";
System.out.println("原始数据: " + originalData);
// 使用公钥加密
String encryptedData = encrypt(originalData, publicKey);
System.out.println("加密后数据: " + encryptedData);
// 使用私钥解密
String decryptedData = decrypt(encryptedData, privateKey);
System.out.println("解密后数据: " + decryptedData);
}
// 生成RSA密钥对
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048); // 密钥长度
return keyPairGenerator.generateKeyPair();
}
// 使用公钥加密数据
public static String encrypt(String data, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
// 使用私钥解密数据
public static String decrypt(String encryptedData, PrivateKey privateKey) throws Exception {
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
}
// 从字符串还原公钥
public static PublicKey getPublicKey(String key) throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(key);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(spec);
}
// 从字符串还原私钥
public static PrivateKey getPrivateKey(String key) throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(key);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(spec);
}
}
2. 使用现有密钥进行加密解密
如果你已经有Base64编码的密钥字符串,可以使用以下方法:
public static void main(String[] args) throws Exception {
// 假设这是已有的Base64编码的公钥和私钥
String publicKeyString = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...";
String privateKeyString = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDA...";
// 从字符串还原密钥
PublicKey publicKey = getPublicKey(publicKeyString);
PrivateKey privateKey = getPrivateKey(privateKeyString);
// 加密解密过程与上面示例相同
String originalData = "测试数据";
String encryptedData = encrypt(originalData, publicKey);
String decryptedData = decrypt(encryptedData, privateKey);
System.out.println("解密结果: " + decryptedData);
}
注意事项
-
密钥长度:示例中使用2048位RSA密钥,这是目前推荐的最小长度。更长的密钥更安全但性能更低。
-
加密限制:RSA算法有加密数据长度限制(对于2048位密钥,最多加密245字节数据)。对于更长的数据,通常使用:
- 对称加密算法(如AES)加密数据
- 用RSA加密对称密钥
-
填充方案:示例中使用"RSA/ECB/PKCS1Padding",这是最常用的填充方案。其他可选方案包括"OAEPWithSHA-256AndMGF1Padding"。
-
异常处理:实际应用中应添加适当的异常处理代码。
-
密钥存储:私钥必须安全存储,建议使用密钥库(KeyStore)或硬件安全模块(HSM)。
如果需要更完整的实现或对特定部分有疑问,可以进一步扩展此代码。