在Java 8中,Base64编码已经成为Java类库的标准。使用方法如下:
String text = "base64 in java8 lib";
String base64 = null;
try {
base64 = Base64.getEncoder().encodeToString(text.getBytes("UTF-8"));
System.out.println("加密:"+base64);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
byte[] bytes = Base64.getDecoder().decode(base64);
System.out.println("解密:" + new String(bytes, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
输出结果:
2019-12-17 09:28:33.793 32763-32763/com.example.recyclearapplication I/System.out: 加密:YmFzZTY0IGluIGphdmE4IGxpYg==
2019-12-17 09:28:33.794 32763-32763/com.example.recyclearapplication I/System.out: 解密:base64 in java8 lib