java实现rsa算法加解密完整代码
时间: 2023-11-11 07:02:33 浏览: 92
很高兴能为您解答问题!以下是Java实现RSA算法加解密的完整代码:
```java
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
public class RSAEncryptionExample {
public static void main(String[] args) throws Exception {
String plainText = "Hello, world!";
// Generate public and private keys
KeyPair keyPair = generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// Encrypt the plaintext using the public key
byte[] cipherText = encrypt(plainText, publicKey);
// Decrypt the ciphertext using the private key
String decryptedText = decrypt(cipherText, privateKey);
// Print the original plaintext, the encrypted ciphertext,
// and the decrypted plaintext to the console
System.out.println("Original plaintext: " + plainText);
System.out.println("Encrypted ciphertext: " + new String(cipherText));
System.out.println("Decrypted plaintext: " + decryptedText);
}
public static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
}
public static byte[] encrypt(String plainText, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(plainText.getBytes());
}
public static String decrypt(byte[] cipherText, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(cipher.doFinal(cipherText));
}
}
```
希望这个代码能够帮助您!如果您有其他问题,请随时提出,我将尽力为您解答。
阅读全文