Understanding Base64 Padding
深度 dive into why Base64 uses = padding, how it works, and when you can safely strip it.
问题
你 see one 或 two '=' characters 在结束的 Base64 输出和 want 到理解其 目的和 当它们能够是 removed.
前置条件
- 基础 Base64 编码知识
- Understanding 的位-级别数据 representation
步骤
-
1. Review the 3-to-4 ratio
Base64 encodes every 3 bytes (24 bits) of input into 4 characters. When the input length is not a multiple of 3, the last group is incomplete and padding fills the gap.
输入Hi (2 bytes)输出SGk= -
2. Count the padding characters
If the input length mod 3 equals 1, two padding characters are added. If it equals 2, one padding character is added. If it equals 0, no padding is needed.
输入A (1 byte) → 2 padding输出QQ== -
3. Decide whether to strip padding
In URL-safe or space-constrained contexts (like JWTs), padding can be stripped because the decoder can infer it from the string length. In standard contexts, keep it for maximum compatibility.
输入QQ==输出QQ (stripped, URL-safe)
预期结果
你能够 predict 数字的 padding characters 从输入长度和 安全 strip 或恢复它们当 needed.
常见错误
- Stripping padding breaks a strict decoder
- Only strip padding when the decoder supports lenient mode or can infer padding from length. Restore padding before passing to strict decoders.
排障指引
- If a decoder rejects a stripped string, re-add = until the length is a multiple of 4.
- Never mix padded and unpadded Base64 in the same data stream.
安全限制
- Padding carries no security meaning. It is purely structural.