用Java实现RSA加密和解密
时间: 2023-09-20 11:12:26 浏览: 92
RSA加密和解密的实现步骤如下:
1. 生成RSA密钥对
```java
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.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[] cipherText = cipher.doFinal(plainText.getBytes());
```
4. 使用私钥解密
```java
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedText = cipher.doFinal(cipherText);
```
完整代码如下:
```java
import javax.crypto.Cipher;
import java.security.*;
public class RSAUtil {
/**
* 生成RSA密钥对
*
* @return KeyPair
* @throws NoSuchAlgorithmException
*/
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(1024);
return keyPairGen.generateKeyPair();
}
/**
* 使用公钥加密
*
* @param plainText 明文
* @param publicKey 公钥
* @return byte[] 加密后的数据
* @throws Exception
*/
public static byte[] encrypt(String plainText, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(plainText.getBytes());
}
/**
* 使用私钥解密
*
* @param cipherText 密文
* @param privateKey 私钥
* @return String 解密后的数据
* @throws Exception
*/
public static String decrypt(byte[] cipherText, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedText = cipher.doFinal(cipherText);
return new String(decryptedText);
}
public static void main(String[] args) throws Exception {
String plainText = "Hello World!";
// 生成密钥对
KeyPair keyPair = generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 加密
byte[] cipherText = encrypt(plainText, publicKey);
// 解密
String decryptedText = decrypt(cipherText, privateKey);
System.out.println("明文: " + plainText);
System.out.println("密文: " + new String(cipherText));
System.out.println("解密后的明文: " + decryptedText);
}
}
```
阅读全文