基礎用法
import base64
# 編碼:bytes -> base64 bytes -> str
data = b'hello world'
encoded = base64.b64encode(data) # b'aGVsbG8gd29ybGQ='
encoded_str = encoded.decode('ascii') # 'aGVsbG8gd29ybGQ='
# 解碼:str -> base64 bytes -> bytes
decoded = base64.b64decode(encoded_str) # b'hello world'
decoded_str = decoded.decode('utf-8') # 'hello world'
print(encoded_str, decoded_str)
核心 API 速查
| 函數 | 輸入 | 輸出 | 說明 |
b64encode(data) | bytes | bytes | 標準 Base64 編碼 (A-Z, a-z, 0-9, +, /, =) |
b64decode(data) | bytes/str | bytes | 標準 Base64 解碼,自動忽略空白字符 |
urlsafe_b64encode(data) | bytes | bytes | URL 安全編碼:+ → -, / → _,去掉填充 = |
urlsafe_b64decode(data) | bytes/str | bytes | URL 安全解碼,自動補全填充 |
b32encode/b32decode | bytes | bytes | Base32 (A-Z, 2-7, =),不區分大小寫,適合大小寫不敏感場景 |
b16encode/b16decode | bytes | bytes | Base16 (Hex),0-9, A-F |
字符串與字節轉換模式
# 字符串 → Base64 字符串
def str_to_b64(s, encoding='utf-8'):
return base64.b64encode(s.encode(encoding)).decode('ascii')
# Base64 字符串 → 字符串
def b64_to_str(b64_str, encoding='utf-8'):
return base64.b64decode(b64_str).decode(encoding)
# 測試
original = "中文測試🚀"
b64 = str_to_b64(original) # '5Lit5paH5a2X77yB'
restored = b64_to_str(b64) # '中文測試🚀'
assert original == restored
URL 安全 Base64 實戰
標準 Base64 包含 + / = 在 URL 中有特殊含義,需轉義。urlsafe_b64encode 自動處理:
import base64, urllib.parse
data = b'redirect=https://example.com/path?query=value'
# 標準編碼 (需額外 urlencode)
std = base64.b64encode(data).decode()
url_encoded = urllib.parse.quote(std) # 雙重編碼
# URL 安全編碼 (可直接用於 URL 參數)
url_safe = base64.urlsafe_b64encode(data).decode().rstrip('=')
# 解碼時需補全填充
def urlsafe_decode(s):
padding = '=' * (-len(s) % 4)
return base64.urlsafe_b64decode(s + padding)
# JWT Token 典型用法
header = base64.urlsafe_b64encode(b'{"alg":"HS256","typ":"JWT"}').decode().rstrip('=')
payload = base64.urlsafe_b64encode(b'{"sub":123,"exp":9999999999}').decode().rstrip('=')
signature = base64.urlsafe_b64encode(b'signature_bytes').decode().rstrip('=')
jwt_token = f"{header}.{payload}.{signature}"
print(jwt_token)
進階場景與最佳實踐
1. 大文件流式編碼 (避免內存溢出)
def encode_file_stream(input_path, output_path, chunk_size=8192):
with open(input_path, 'rb') as infile, open(output_path, 'wb') as outfile:
encoder = base64.encodebytes # 每 57 字節輸出 76 字節 + 換行
while True:
chunk = infile.read(chunk_size)
if not chunk:
break
outfile.write(encoder(chunk))
# 對應解碼: base64.decodebytes(infile.read(chunk_size))
2. 自定義字符表 (非標準 Base64)
import string
custom_alphabet = string.ascii_uppercase + string.ascii_lowercase + string.digits + '-_'
# 需自行實現編解碼邏輯,或使用 base64 模塊內部 _translate (不穩定)
# 建議:標準 Base64 + 字符替換
def custom_encode(data):
std = base64.b64encode(data).decode()
return std.translate(str.maketrans('+/', '-_')).rstrip('=')
def custom_decode(s):
std = s.translate(str.maketrans('-_', '+/'))
padding = '=' * (-len(std) % 4)
return base64.b64decode(std + padding)
3. 常見錯誤與調試
| 錯誤 | 原因 | 修正 |
binascii.Error: Incorrect padding | 解碼字符串長度非 4 的倍數 | 補全 = 至 4 的倍數:s + '=' * (-len(s) % 4) |
UnicodeDecodeError | 解碼後字節非目標編碼 | 確認原始編碼,或用 errors='replace' |
字符串直接傳給 b64decode | Python 3 接受 str 但隱式用 ASCII 解碼 | 顯式 .encode('ascii') 或傳 bytes |
總結
- 核心:
b64encode/b64decode 處理 bytes,字符串需自行 encode/decode。
- URL 场景用
urlsafe_b64encode + .rstrip('='),解碼前補填充。
- 大文件用流式
encodebytes/decodebytes。
- 嚴禁自定義字符表除非極特殊需求,標準 Base64 互操作性最強。