// JUnit Test 测试
public static void main(String[] args){
String s = "xyzXYZ";
System.out.println("The base64 encode string value is " + base64Encode(s));
System.out.println("The base64 decode string value is " + base64Decode(base64Encode(s)));
}
// 编码
public static String base64Encode(String str) {
byte[] encodedBytes = java.util.Base64.getEncoder().encode(str.getBytes());
return new String(encodedBytes,java.nio.charset.Charset.forName("UTF-8"));
}
// 解码
public static String base64Decode(String str) {
String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
//判断字符串是不是base64编码,如果不是,直接返回
if(Pattern.matches(base64Pattern, str))
{
byte[] decodedBytes = java.util.Base64.getDecoder().decode(str.getBytes());
return new String(decodedBytes, java.nio.charset.Charset.forName("UTF-8"));
}
return str;
}