记录一下java base64编码和解码,也就是通常说的base6解密和base64加密
java(java8)中的base64工具 java.util.Base64
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
* 蚂蚁舞
*/
public class ConvertBase64Main {
public static void main(String[] args) throws UnsupportedEncodingException {
// Java字符串转Base64
String str = "myw-蚂蚁也会跳舞";
byte [] strBytes = str.getBytes();
String str_hex = Base64.getEncoder().encodeToString(strBytes);
System.out.println(str_hex); // bXl3LeiaguiageS5n+S8mui3s+iIng==
byte [] strBytes_utf_8 = str.getBytes(StandardCharsets.UTF_8);
String str_hex_utf_8 = Base64.getEncoder().encodeToString(strBytes_utf_8);
System.out.println(str_hex_utf_8); // bXl3LeiaguiageS5n+S8mui3s+iIng==
byte [] strBytes_gbk = str.getBytes("GBK");
String str_hex_gbk = Base64.getEncoder().encodeToString(strBytes_gbk);
System.out.println(str_hex_gbk); // bXl3LcLs0s/SsrvhzPjO6A==
String str_base64 = "bXl3LeiaguiageS5n+S8mui3s+iIni1teXlodHc=";
String str_base64_gbk = "bXl3LcLs0s/SsrvhzPjO6C1teXlodHc=";
// 将Base64编码转为Java字符串
byte [] base64Bytes = Base64.getDecoder().decode(str_base64);
String javaStr = new String(base64Bytes);
System.out.println(javaStr); // myw-蚂蚁也会跳舞-myyhtw
byte [] base64Bytes_utf_8 = Base64.getDecoder().decode(str_base64);
String javaStr_utf_8 = new String(base64Bytes_utf_8, StandardCharsets.UTF_8);
System.out.println(javaStr_utf_8); // myw-蚂蚁也会跳舞-myyhtw
byte [] base64Bytes_gbk = Base64.getDecoder().decode(str_base64_gbk);
String javaStr_gbk = new String(base64Bytes_gbk, "GBK");
System.out.println(javaStr_gbk); // myw-蚂蚁也会跳舞-myyhtw
}
}