コンテンツへスキップ
uencoder

Base64 パディングの理解

Base64 が = パディングを使う理由、その仕組み、安全に取り除けるケースを深く掘り下げます。

问题

Base64 の出力末尾に 1 つか 2 つの = 文字があり、その役割と、いつ除去できるのかを理解したい状況です。

前提条件

  • Base64 エンコードの基礎知識
  • ビットレベルのデータ表現の理解

ステップ

  1. 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. 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. 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)

期待される結果

入力の長さからパディング文字数を予測し、必要に応じて安全に除去・復元できるようになります。

よくあるエラー

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.

関連ツール

関連用語

参考链接