コンテンツへスキップ
uencoder

パディング方式の理解

PKCS#7、ゼロパディング、ISO 10126 を比較し、ブロック暗号でパディングが重要な理由を学びます。

问题

ブロック暗号は入力がブロックサイズの倍数であることを要求しますが、データがそうなっていないため、正しくパディングする必要があります。

前提条件

  • ブロック暗号の理解
  • ブロックサイズ(AES は 16 バイト)に関する知識

ステップ

  1. 1. Understand why padding is needed

    Block ciphers like AES process data in fixed-size blocks (16 bytes). If the plaintext is not a multiple of the block size, the last block is incomplete. Padding adds bytes to fill the block and must be removable without ambiguity.

    入力
    13 bytes of data
    输出
    pad to 16 bytes
  2. 2. Choose a padding scheme

    PKCS#7 (the standard for AES) appends N bytes each with value N, where N is the number of padding bytes. If the data is already block-aligned, a full block of padding is added. Zero padding appends zeros but is ambiguous if the data ends with zeros. ISO 10126 uses random bytes with the last byte indicating the count.

    入力
    PKCS#7 on 'test' (4 bytes)
    输出
    'test' + 0x0C × 12
  3. 3. Remove padding after decryption

    After decryption, strip the padding to recover the original. For PKCS#7, read the last byte's value N and remove N bytes, verifying they all equal N. If verification fails, the padding is invalid, indicating a wrong key or tampering.

    入力
    'test' + 0x0C × 12
    输出
    'test' (4 bytes)

期待される結果

有効なブロック整列暗号文に暗号化され、復号後に曖昧さなくパディングが除去される、正しくパディングされた平文。

よくあるエラー

Using zero padding on data that ends with zeros
Zero padding is ambiguous. Use PKCS#7, which always adds a padding block and is unambiguous.
Not adding padding when data is block-aligned
PKCS#7 always adds at least one byte. Without this, you cannot distinguish padded from unpadded data.

トラブルシューティング指引

  • If unpadding fails with 'invalid padding', the key is likely wrong or the ciphertext was corrupted.
  • Use GCM or CTR mode to avoid padding entirely if possible.

セキュリティ上の制限

  • Padding oracle attacks exploit padding validation errors. Use authenticated encryption (GCM) to prevent them.

関連ツール

関連用語

参考链接