使用RSA算法对数据进行加密和解密需要使用公钥和私钥。以下是一个简单的示例,展示了如何使用RSA加密算法进行数据加密和解密:
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;
public class RSAEncryptionExample {
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
}
public static String encryptData(String data, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decryptData(String encryptedData, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
public static void main(String[] args) throws Exception {
String plainText = "Hello, World!";
// 生成密钥对
KeyPair keyPair = generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 加密数据
String encryptedText = encryptData(plainText, publicKey);
System.out.println("Encrypted Data: " + encryptedText);
// 解密数据
String decryptedText = decryptData(encryptedText, privateKey);
System.out.println("Decrypted Data: " + decryptedText);
}
}
在上述示例中,首先调用generateKeyPair()
方法生成RSA算法所需的公钥和私钥。
然后,使用公钥对数据进行加密,调用 encryptData()
方法,使用 RSA 加密算法进行数据加密,返回加密后的结果。
接下来,使用私钥对数据进行解密,调用 decryptData()
方法,使用 RSA 加密算法进行数据解密,返回解密后的结果。
最后,将加密和解密后的数据输出。
这是一个简单的示例,仅用于演示 RSA 加密和解密的基本原理。在实际使用中,需要更多的安全考虑和实践。
注意:RSA算法通常用于加密较小的数据块,对于更大的数据块,通常使用对称加密算法先对数据进行加密,然后使用RSA算法对对称密钥进行加密。
希望对你有所帮助!如果有其他问题,请随时提问。