hutool用rsa 加密解密 例子
时间: 2024-04-09 10:22:35 浏览: 26
以下是使用Hutool进行RSA加密和解密的例子:
```java
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
public class RSATest {
public static void main(String[] args) {
// 生成RSA密钥对
RSA rsa = new RSA();
String publicKey = rsa.getPublicKeyBase64();
String privateKey = rsa.getPrivateKeyBase64();
System.out.println("公钥:" + publicKey);
System.out.println("私钥:" + privateKey);
// 加密
String data = "Hello, World!";
byte[] encrypt = rsa.encrypt(data.getBytes(), KeyType.PublicKey);
String encryptStr = cn.hutool.core.codec.Base64.encode(encrypt);
System.out.println("加密后的数据:" + encryptStr);
// 解密
byte[] decrypt = rsa.decrypt(cn.hutool.core.codec.Base64.decode(encryptStr), KeyType.PrivateKey);
String decryptStr = new String(decrypt);
System.out.println("解密后的数据:" + decryptStr);
}
}
```
在上面的例子中,我们首先使用`RSA`类生成RSA密钥对,然后使用公钥对数据进行加密,使用私钥对加密后的数据进行解密。在加密和解密时,我们需要指定密钥类型(公钥或私钥)。最后,我们将加密和解密后的数据进行输出验证。注意,我们在输出加密后的数据时,使用了`cn.hutool.core.codec.Base64.encode`方法将加密后的字节数组转换为Base64字符串,以便更方便地输出和传输。同样,在解密时,我们使用了`cn.hutool.core.codec.Base64.decode`方法将Base64字符串转换为字节数组。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)