Base64 將任意二進制數據編碼為 64 個可打印字符(A-Z, a-z, 0-9, +, /),常用於郵件傳輸、數據嵌入。編碼後體積膨脹為原始 4/3 倍,長度為 4 的倍數。
| 字符 | A | d | 3 | |
|---|---|---|---|---|
| ASCII | 65 | 100 | 51 | |
| 二進制 | 01000001 | 01100100 | 00110011 | |
| 6位分組 | 010000 010110 010000 110011 | |||
| 補位後 | 16 | 22 | 16 | 51 |
| Base64字符 | Q | W | Q | z |
結果:QWQz

<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.68</version>
</dependency>
import org.bouncycastle.util.encoders.Base64;
public class Base64Util {
static final String ENCODING = "UTF-8";
public static String encode(String data) throws UnsupportedEncodingException {
return new String(Base64.encode(data.getBytes(ENCODING)), ENCODING);
}
public static String decode(String data) throws UnsupportedEncodingException {
return new String(Base64.decode(data.getBytes(ENCODING)), ENCODING);
}
}
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
import org.apache.commons.codec.binary.Base64;
public class Base64Util {
static final String ENCODING = "UTF-8";
// 標準編碼
public static String encode(String data) {
return new String(Base64.encodeBase64(data.getBytes(ENCODING)), ENCODING);
}
// RFC 標準編碼 (含換行)
public static String encodeSafe(String data) {
return new String(Base64.encodeBase64(data.getBytes(ENCODING), true), ENCODING);
}
public static String decode(String data) {
return new String(Base64.decodeBase64(data.getBytes(ENCODING)), ENCODING);
}
}
| 特性 | Bouncy Castle | Commons Codec |
|---|---|---|
| RFC 標準合規 | 否 | 是 (encodeBase64(bytes, true)) |
| API 簡潔度 | 高 | 高 |
| 依賴體積 | 較大 (含加密算法) | 極小 (專注編碼) |
| 推薦場景 | 已引入 BC 做加密 | 純編碼需求、標準合規 |
import java.util.Base64;
// 標準編碼
String encoded = Base64.getEncoder().encodeToString("Ad3".getBytes(StandardCharsets.UTF_8));
// URL 安全編碼
String urlSafe = Base64.getUrlEncoder().encodeToString(bytes);
// MIME 編碼 (含換行)
String mime = Base64.getMimeEncoder().encodeToString(bytes);
// 解碼
byte[] decoded = Base64.getDecoder().decode(encoded);
Java 8+ 項目**首選內置 java.util.Base64**,零依賴、標準合規、性能優異。
public static void main(String[] args) throws Exception {
String original = "Ad3";
String encoded = Base64Util.encodeSafe(original);
String decoded = Base64Util.decode(encoded);
System.out.println("原文: " + original);
System.out.println("編碼: " + encoded); // QWQz
System.out.println("解碼: " + decoded);
assert original.equals(decoded);
}