springboot中使用base64加密
时间: 2023-10-11 09:05:10 浏览: 45
在Spring Boot中,可以使用Java内置的Base64类来实现加密和解密操作。以下是一个使用Base64加密字符串的示例:
```java
import java.util.Base64;
public class Base64Utils {
public static String encode(String text) {
byte[] bytes = text.getBytes();
return Base64.getEncoder().encodeToString(bytes);
}
public static String decode(String text) {
byte[] bytes = Base64.getDecoder().decode(text);
return new String(bytes);
}
}
```
在上面的代码中,我们使用了Java 8的Base64类进行加密和解密操作。在`encode`方法中,首先将输入字符串转换为字节数组,然后使用`Base64.getEncoder()`方法获取Base64编码器,并使用`encodeToString`方法将字节数组转换为Base64字符串。在`decode`方法中,我们使用`Base64.getDecoder()`方法获取Base64解码器,并使用`decode`方法将Base64字符串转换为字节数组,最后使用`new String`方法将字节数组转换为字符串。
使用示例:
```java
String text = "Hello, world!";
String encodedText = Base64Utils.encode(text);
System.out.println("Encoded text: " + encodedText);
String decodedText = Base64Utils.decode(encodedText);
System.out.println("Decoded text: " + decodedText);
```
输出结果:
```
Encoded text: SGVsbG8sIHdvcmxkIQ==
Decoded text: Hello, world!
```
注意:Base64加密后的字符串会比原始字符串长,因为它是用6位的二进制数表示一个字符。