Batu Lab NotesPractical developer guides

Reject non-alphabet characters during strict Base64 decoding

By Batu ยท English technical notes

Also published in our primary archive.

Reject non-alphabet characters during strict Base64 decoding

How can Python Base64 decoding reject invalid characters? Pass validate=True to base64.b64decode(). With its default validate=False, Python discards characters outside the selected Base64 alphabet before checking padding. That means the altered fixture b'YWJj$ZA==' silently becomes the same effective Base64 data as b'YWJjZA==' and decodes to b'abcd'.

The experiment makes that contrast explicit. First, permissive decoding returns bytes, which is a finding about the input rather than evidence that the original token was clean. Next, strict decoding raises binascii.Error; the code records the exception class instead of depending on exception-message wording. Finally, the valid control is decoded with the same strict setting and returns b'abcd'.

Use strict validation when a field is supposed to contain one complete Base64 value and punctuation, whitespace, or copied delimiters should be rejected. It does not authenticate decoded bytes, establish where they came from, or select URL-safe alphabet characters automatically; use the appropriate altchars setting when that format is intended. b64decode accepts bytes-like input and ASCII strings in modern Python; ASCII string support was added in Python 3.3. The documented validate behavior is the reason the two inputs differ here. Python base64 documentation

AI assistance disclosure: This article was drafted with AI assistance and checked against the cited documentation and a synthetic example.

import base64
import binascii

altered = b"YWJj$ZA=="
control = b"YWJjZA=="

permissive = base64.b64decode(altered)
assert permissive == b"abcd"

try:
    base64.b64decode(altered, validate=True)
except binascii.Error as error:
    strict_result = type(error).__name__
else:
    raise AssertionError("strict decoding should reject '$'")

valid = base64.b64decode(control, validate=True)
assert valid == b"abcd"

print(f"permissive={permissive!r}")
print(f"strict={strict_result}")
print(f"control={valid!r}")
permissive=b'abcd'
strict=Error
control=b'abcd'