Base64是網絡上最常見的用於傳輸8Bit字節碼的編碼方式之一,Base64就是一種基於64個可打印字符來表示二進制數據的方法。可查看RFC2045~RFC2049,上面有MIME的詳細規范。
Base64編碼是從二進制到字符的過程,可用於在HTTP環境下傳遞較長的標識信息。例如,在Java Persistence系統Hibernate中,就采用了Base64來將一個較長的唯一標識符(一般為128-bit的UUID)編碼為一個字符串,用作HTTP表單和HTTP GET URL中的參數。在其他應用程序中,也常常需要把二進制數據編碼為適合放在URL(包括隱藏表單域)中的形式。此時,采用Base64編碼具有不可讀性,需要解碼后才能閱讀。
Java8.0之前,添加Jar包
Java 8之后的作法
Java 8的java.util套件中,新增了Base64的類別,可以用來處理Base64的編碼與解碼,用法如下:
import java.nio.charset.StandardCharsets; public class ABase64 { public static void main(String[] args) { String password = "Hello 123456"; //加密 String encoded = java.util.Base64.getEncoder().encodeToString(password.getBytes(StandardCharsets.UTF_8)); //解密 String decoded = new String(java.util.Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8); System.out.println(encoded); System.out.println(decoded); showBase64(); } private static void showBase64() { try { final java.util.Base64.Decoder decoder = java.util.Base64.getDecoder(); final java.util.Base64.Encoder encoder = java.util.Base64.getEncoder(); final String text = "Hello 小笨蛋"; final byte[] textByte = text.getBytes("UTF-8"); //編碼 final String encodedText = encoder.encodeToString(textByte); System.out.println(encodedText); //解碼 System.out.println(new String(decoder.decode(encodedText), "UTF-8")); } catch (Exception e) { e.printStackTrace(); } } }
日志:

