編碼規則
- 將輸入資料以 3 位元組 (24 bits) 為一組。
- 將 24 bits 切成 4 組,每組 6 bits。
- 每組 6 bits 高位補兩個 0 湊成 1 個位元組 (8 bits)。
- 依 Base64 字元表 (A-Z, a-z, 0-9, +, /) 查詢對應字元。
- 不足 3 位元組時,以 0 位元組補齊,輸出字元以
= 補齊 (1 或 2 個)。
範例: "ABC" 編碼過程
ASCII: A(65) B(66) C(67)
二進位: 01000001 01000010 01000011
合併: 010000010100001001000011
切6bits: 010000 010100 001001 000011
補0: 00010000 00010100 00001001 00000011
十進位: 16 20 19 3
Base64: Q U J D
結果: "QUJD"
C# 完整實作
編碼方法
public static string Base64Encode(string message)
{
char[] base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".ToCharArray();
byte[] bytes = Encoding.Default.GetBytes(message);
int len = bytes.Length;
int groups = (len + 2) / 3; // 向上取整
StringBuilder sb = new StringBuilder(groups * 4);
for (int i = 0; i < groups; i++)
{
byte b1 = i * 3 < len ? bytes[i * 3] : (byte)0;
byte b2 = i * 3 + 1 < len ? bytes[i * 3 + 1] : (byte)0;
byte b3 = i * 3 + 2 < len ? bytes[i * 3 + 2] : (byte)0;
int[] idx = new int[4];
idx[0] = b1 >> 2;
idx[1] = ((b1 & 0x03) << 4) | (b2 >> 4);
idx[2] = (i * 3 + 1 < len) ? ((b2 & 0x0F) << 2) | (b3 >> 6) : 64;
idx[3] = (i * 3 + 2 < len) ? (b3 & 0x3F) : 64;
sb.Append(base64Chars[idx[0]]);
sb.Append(base64Chars[idx[1]]);
sb.Append(base64Chars[idx[2]]);
sb.Append(base64Chars[idx[3]]);
}
return sb.ToString();
}
解碼方法
public static string Base64Decode(string message)
{
if (message.Length % 4 != 0)
throw new ArgumentException("無效的 Base64 字串長度");
string base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
int groups = message.Length / 4;
List output = new List(groups * 3);
for (int i = 0; i < groups; i++)
{
int i1 = base64Chars.IndexOf(message[i * 4]);
int i2 = base64Chars.IndexOf(message[i * 4 + 1]);
int i3 = base64Chars.IndexOf(message[i * 4 + 2]);
int i4 = base64Chars.IndexOf(message[i * 4 + 3]);
if (i1 < 0 || i2 < 0 || i3 < 0 || i4 < 0)
throw new ArgumentException("包含非 Base64 字元");
byte b1 = (byte)((i1 << 2) | (i2 >> 4));
output.Add(b1);
if (i3 != 64)
{
byte b2 = (byte)((i2 << 4) | (i3 >> 2));
output.Add(b2);
}
if (i4 != 64)
{
byte b3 = (byte)((i3 << 6) | i4);
output.Add(b3);
}
}
return Encoding.Default.GetString(output.ToArray());
}
實務建議
- 實際專案請直接使用
Convert.ToBase64String(byte[]) 與 Convert.FromBase64String(string),經過最佳化且符合 RFC 4648 標準。
- 本文實作僅供教學理解演算法細節。
- 檔案加密/解密流程:讀檔 → 位元組陣列 → Base64 編碼 → 寫檔;解碼反之。