fjordtools / Errors / Python: Incorrect padding

binascii.Error: Incorrect padding

Base64 text must have a length that is a multiple of four, padded with equals signs. Python's decoder refuses text that is shorter than that. URLs, tokens and some APIs drop the padding to save space, so add it back before decoding. If the text was cut off, no padding will help.

Fjordtools team · Seen in Python 3 · Published · 1 min read

How browsers word it

Python 3binascii.Error: Incorrect padding
JavaIllegalArgumentException: Input byte array has incorrect ending byte at 7

Common causes

  1. The padding was removed

    Base64 in URLs and JWTs usually has no = signs. This tool accepts that and decodes the text, but Python and some other decoders do not.

    Input

    SGVsbG8

    Base64 says

    Hello
  2. The text was cut off

    A length that leaves one character over cannot be Base64, with or without padding. Part of the text is missing.

    Input

    SGVsb

    Base64 says

    The length is not valid for Base64 (one character too many or too few)
  3. Too many equals signs

    Padding is at most two = characters at the very end.

    Input

    SGVsbG8===

    Base64 says

    Too much padding. Base64 ends with at most two = characters

How to fix it

  1. Add = signs until the length is a multiple of four: in Python, text + "=" * (-len(text) % 4).
  2. Check that the text was not cut off by a log, a form field or a length limit.
  3. For the URL-safe alphabet (- and _), use urlsafe_b64decode, after adding the padding.
  4. Paste the text into the Base64 tool to see whether it decodes.

Related errors

More error explainers are coming

See all errors.