java rsa 加密解密算法
时间: 2023-07-07 16:31:06 浏览: 105
RSA是一种非对称加密算法,它是由 Ron Rivest, Adi Shamir 和 Leonard Adleman 在1977年提出的。下面是Java实现RSA加密解密算法的示例代码:
1. 生成密钥对
```java
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
public class RSAUtil {
public static KeyPair getKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
}
}
```
2. 加密
```java
import java.security.Key;
import javax.crypto.Cipher;
public class RSAUtil {
public static byte[] encrypt(Key publicKey, byte[] data) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
}
}
```
3. 解密
```java
import java.security.Key;
import javax.crypto.Cipher;
public class RSAUtil {
public static byte[] decrypt(Key privateKey, byte[] data) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
}
}
```
示例代码中的 `getKeyPair` 方法用于生成公钥和私钥的密钥对,`encrypt` 方法用于加密数据,`decrypt` 方法用于解密数据。需要注意的是,加密和解密时需要使用不同的密钥。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)