java rsa 加解密实现
时间: 2023-08-01 21:14:17 浏览: 165
RSA算法是一种非对称加密算法,可以实现加密和解密操作。以下是Java中使用RSA算法进行加解密的示例代码:
1. 生成密钥对
```java
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
public class RSAUtil {
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
}
}
```
2. 加密数据
```java
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
public class RSAUtil {
// 省略 generateKeyPair 方法
public static String encrypt(String data, String publicKey) throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(publicKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
Key key = keyFactory.generatePublic(new PKCS8EncodedKeySpec(keyBytes));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] dataBytes = data.getBytes();
byte[] encryptedDataBytes = cipher.doFinal(dataBytes);
return Base64.getEncoder().encodeToString(encryptedDataBytes);
}
}
```
3. 解密数据
```java
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
public class RSAUtil {
// 省略 generateKeyPair 方法和 encrypt 方法
public static String decrypt(String encryptedData, String privateKey) throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(privateKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
Key key = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData);
byte[] dataBytes = cipher.doFinal(encryptedDataBytes);
return new String(dataBytes);
}
}
```
示例代码中使用了Java自带的Base64类进行数据编码和解码,可以自行替换为其他编码方式。
阅读全文