以下是一个使用Java进行RSA加密和解密的简单示例。这个示例使用Java的标准加密库,不需要额外的库。
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.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 {
String plainText = "这是要加密的数据";
// 生成RSA密钥对
KeyPair keyPair = generateRSAKeyPair();
// 获取公钥和私钥
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 加密
String encryptedText = encrypt(plainText, publicKey);
System.out.println("加密后的数据: " + encryptedText);
// 解密
String decryptedText = decrypt(encryptedText, privateKey);
System.out.println("解密后的数据: " + decryptedText);
}
public static KeyPair generateRSAKeyPair() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048); // RSA密钥长度,可以根据需要更改
return keyPairGenerator.generateKeyPair();
}
public static String encrypt(String plainText, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
}
}
在上述示例中,`generateRSAKeyPair`方法生成了RSA密钥对,`encrypt`方法接受明文和公钥,然后返回加密后的Base64编码字符串。`decrypt`方法接受加密的Base64编码字符串和私钥,然后返回解密后的明文。
请注意,RSA密钥长度可以根据需要进行调整,示例中使用了2048位的密钥长度。在实际应用中,密钥的生成和管理需要更加安全