springboot非对称加解密
时间: 2023-10-12 20:01:00 浏览: 51
Spring Boot本身并没有提供非对称加解密的功能,但可以通过引入相关的依赖来实现。
一种常见的非对称加解密算法是RSA,可以使用Java中的`javax.crypto`包来进行操作。首先,需要生成RSA密钥对,包括公钥和私钥。可以使用`KeyPairGenerator`类来生成密钥对,示例如下:
```java
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048); // 设置密钥长度
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
```
接下来,可以使用公钥对数据进行加密,私钥对数据进行解密。示例如下:
```java
// 加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedData = cipher.doFinal(plainText.getBytes());
// 解密
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedData = cipher.doFinal(encryptedData);