一、Base64簡介
Base64是一種編碼與解碼方式,用於將二進位制資料編碼為64個可列印字元,或者相反操作。
二、知識點
2.1 Base64字元
Base64有64個可列印字元,包括:A-Z,a-z,0-9,+,/,它們的編碼分別從0到63。
2.2 Base64實現
Base64內部實現是:將二進位制流以6位分組,然後每個分組高位補2個0(計算機是8位存數),這樣每個組值就是在64以內,然後轉為對應的編碼。
三、例項
3.1 jdk原生實現
實現方式一,藉助jdk自身的BASE64Encoder和BASE64Decoder,示例如下:
public class Base64Main {
public static void main(String[] args) throws Exception {
String source = "study hard and make progress everyday";
System.out.println("source : "+ source);
String result = base64Encode(source.getBytes("utf8")); //編碼
System.out.println("encode result : " + result);
String rawSource = new String(base64Decode(result),"utf8"); //解碼
System.out.println("decode result : "+ rawSource);
}
//編碼
static String base64Encode(byte[] source) {
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(source);
}
//解碼
static byte[] base64Decode(String source){
try {
BASE64Decoder decoder = new BASE64Decoder();
return decoder.decodeBuffer(source);
} catch (IOException e) {
}
return null;
}
}
執行結果:
source : study hard and make progress everyday
encode result : c3R1ZHkgaGFyZCBhbmQgbWFrZSBwcm9ncmVzcyBldmVyeWRheQ==
decode result : study hard and make progress everyday
3.2 commons-codec包實現
實現方式二,藉助commons-codec包,示例如下:
新增maven依賴:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
程式碼:
public class Base64FromCommonsMain {
public static void main(String[] args) throws Exception {
String source = "study hard and make progress everyday";
System.out.println("source : "+ source);
String result = Base64.encodeBase64String(source.getBytes("utf8")); //編碼
System.out.println("encode result : " + result);
String rawSource = new String(Base64.decodeBase64(result),"utf8"); //解碼
System.out.println("decode result : "+ rawSource);
}
}
執行結果:
source : study hard and make progress everyday
encode result : c3R1ZHkgaGFyZCBhbmQgbWFrZSBwcm9ncmVzcyBldmVyeWRheQ==
decode result : study hard and make progress everyday