Base64 將任意二進位資料轉換為 64 個可列印字元(A-Z、a-z、0-9、+、/)組成的字串。每 3 個位元組(24 bits)分為 4 組各 6 bits,對應查表得到 4 個字元。編碼後體積約增加 33%,但可安全傳輸於純文字環境(Email、URL、Cookie、XML/JSON)。
import base64
# 編碼
encoded = base64.b64encode(b'binary\x00string')
print(encoded) # b'YmluYXJ5AHN0cmluZw=='
# 解碼
decoded = base64.b64decode(encoded)
print(decoded) # b'binary\x00string'
標準 Base64 包含 +、/ 在 URL 中需轉義,urlsafe_b64encode 將其替換為 -、_:
>> base64.b64encode(b'i\xb7\x1d\xfb\xef\xff')
b'abcd++//'
>>> base64.urlsafe_b64encode(b'i\xb7\x1d\xfb\xef\xff')
b'abcd--__'
>>> base64.urlsafe_b64decode(b'abcd--__')
b'i\xb7\x1d\xfb\xef\xff'
某些場景會移除結尾的 = 填充,導致標準解碼失敗。解碼前補齊長度為 4 的倍數即可:
def safe_b64decode(s):
"""支援無填充字元的 Base64 解碼"""
s = s.decode() if isinstance(s, bytes) else s
# 補齊 = 至長度為 4 的倍數
s += '=' * (-len(s) % 4)
return base64.b64decode(s)
# 測試
print(safe_b64decode('YWJjZA')) # b'abcd'
print(safe_b64decode('YWJjZA==')) # b'abcd'
Base64 不是加密,僅是編碼。任何人皆可解碼還原原始資料。若需機密性,請搭配 AES 等加密演算法使用。