hutools 非对称加密
时间: 2024-04-09 08:23:00 浏览: 11
Hutools是一个Java工具库,其中包含了非对称加密的实现。非对称加密是一种加密方式,它使用了一对密钥,即公钥和私钥。公钥可以公开,任何人都可以使用它来加密数据,但只有持有私钥的人才能解密数据。这种加密方式常用于数字签名、身份验证等场景。
Hutools中提供了RSA算法的实现,可以方便地进行非对称加密。使用Hutools进行RSA加密的示例代码如下:
```java
// 生成公钥和私钥
KeyPair keyPair = SecureUtil.generateKeyPair("RSA");
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// 使用公钥加密数据
String data = "Hello, world!";
byte[] encrypted = SecureUtil.rsa(publicKey).encrypt(data.getBytes(), KeyType.PublicKey);
// 使用私钥解密数据
byte[] decrypted = SecureUtil.rsa(privateKey).decrypt(encrypted, KeyType.PrivateKey);
String result = new String(decrypted);
System.out.println(result); // 输出:Hello, world!
```