java使用RSA加密字符串
时间: 2023-09-16 18:06:37 浏览: 94
rsa.rar_rsa_字符串加密
Java中使用RSA加密字符串的步骤如下:
1. 生成RSA密钥对
```java
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
```
2. 获取公钥和私钥
```java
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
```
3. 使用公钥加密字符串
```java
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
```
4. 使用私钥解密字符串
```java
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
String decryptedText = new String(decryptedBytes);
```
完整代码示例:
```java
import java.security.*;
import javax.crypto.*;
public class RSAEncryptionExample {
public static void main(String[] args) throws Exception {
String plainText = "Hello, world!";
// 生成RSA密钥对
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// 获取公钥和私钥
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 使用公钥加密字符串
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
// 使用私钥解密字符串
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
String decryptedText = new String(decryptedBytes);
System.out.println("Plain Text: " + plainText);
System.out.println("Encrypted Text: " + new String(encryptedBytes));
System.out.println("Decrypted Text: " + decryptedText);
}
}
```
注意:RSA加密算法是一种非常耗时的加密算法,因此在加密大量数据时会影响性能。建议使用对称加密算法来加密大量数据。
阅读全文