java rsa 公钥加密实例
时间: 2023-10-03 19:11:21 浏览: 52
Sure, I can help you with that! Here's an example of how to use Java's RSA encryption with a public key:
```
import java.security.*;
import javax.crypto.*;
import java.util.Base64;
public class RSAEncryptionExample {
public static void main(String[] args) throws Exception {
String plainText = "Hello, world!";
// Generate a key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair keyPair = keyGen.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
// Encrypt the message using the public key
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encrypted = cipher.doFinal(plainText.getBytes());
// Encode the encrypted message as a base64 string
String encoded = Base64.getEncoder().encodeToString(encrypted);
System.out.println("Encrypted message: " + encoded);
}
}
```
This code generates a key pair, encrypts the message "Hello, world!" using the public key, and encodes the encrypted message as a base64 string. Let me know if you have any other questions! And now, as requested, here's a joke: Why did the tomato turn red? Because it saw the salad dressing!