Watch at Ease看見世界,讀懂生活。

科技 · 實用指南

Python 的 validate=True 仍接受兩種 Base64 寫法?強制規範 padding bits

嚴格 alphabet 檢查不等於 RFC 4648 canonical encoding。Python 3.15+ 用 canonical=True;舊版嚴格 decode 後 re-encode 並精確比較。

原創流程圖:分開 Base64 syntax、byte decode 與 canonical gate。
原創示意圖:先驗 alphabet,再 decode,最後強制單一 spelling。 Watch at Ease

validate=True 會檢查 alphabet 與 padding 結構,但 Python 3.14 以前仍可能接受未使用 padding bits 非零的 Base64 alias;多個字串會 decode 成同一 bytes。

Python 3.15 用 canonical=True;舊版要在同一 protocol policy 下嚴格 decode、re-encode,再精確比較。canonical spelling 也不等於 authentication。

1. 結果確實如此

CPython 3.12.14 會把三個例子都 decode 成 c1。validate=True 不等於舊版的 zero-pad-bit 檢查。

合規 encoder 只產生一個 canonical spelling;多對一來自 decoder 忽略未使用低位。

2. alias 的位元原因

一個 input byte 只使用第二個 Base64 symbol 的高兩位,剩餘四位是 pad bits。RFC 4648 要求 encoder 設零。

syntax valid、decoded bytes correct、text canonical 是三個不同判斷。

3. Python 3.15

使用 base64.b64decode(value, validate=True, canonical=True),alias 會拋 binascii.Error。

同時明確 padded、whitespace 與 URL-safe policy。

4. Python 3.14 以前

strict decode 後以 base64.b64encode re-encode,要求與 ASCII input 完全一致。

不要任意補等號;unpadded 或 URL-safe protocol 必須先定義自己的 canonical form。

5. 何時重要

Base64 text 作為 database key、cache key、dedupe、allow-list、signature input 或 audit id 時,alias 會拆分 identity。

可行時直接比較 decoded bytes;否則在 boundary 強制 canonical text。

6. 不等於認證

惡意 bytes 也能有 canonical encoding。信任仍需 MAC 或 digital signature。

測試 canonical value、alias、invalid alphabet、bad padding 與每個 protocol variant。

原創矩陣:比較 validate、canonical、re-encode 與 cryptographic authentication。
原創示意圖:canonicalization 給唯一寫法;signature 或 MAC 才提供信任。 Watch at Ease