Validate Canonical Base64 Fields in Python

A configuration stores a binary record identifier as Base64 text. If the importer accepts several spellings of the same bytes, a text-based duplicate check can disagree with a later byte-based lookup. Define one accepted spelling at the import boundary, before storing the identifier.

These examples use Python 3.10 or later and the standard library. The field accepts standard Base64 with required padding where needed, no whitespace, and an empty string for an empty byte sequence. Its application limit is 256 decoded bytes.

Observe What the Default Decoder Ignores

Run this standalone example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import base64
import binascii

print(base64.b64decode("Z g==\n"))
try:
    base64.b64decode("Z g==\n", validate=True)
except binascii.Error:
    print("Rejected: unexpected whitespace")
# b'f'
# Rejected: unexpected whitespace

The Python Base64 reference explains that the default decoder discards characters outside the alphabet before checking padding. Passing validate=True makes those characters an error. Do not call strip() or remove line breaks first when the configuration contract forbids them: that would repair input the field is meant to reject.

Compare the Input with Its Re-Encoded Bytes

Strict decoding alone does not establish a unique spelling. In a final group that encodes one byte, the second symbol has four unused bits. Nonzero values in those bits can produce another string that decodes to the same byte. RFC 4648 section 3.5 describes why zero padding bits matter for canonical encoding.

Save this as base64_field.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import base64
import binascii

MAX_BYTES = 256
MAX_TEXT = 4 * ((MAX_BYTES + 2) // 3)


def parse_base64_field(text):
    if not isinstance(text, str):
        raise TypeError("Base64 field must be a string")
    if len(text) > MAX_TEXT:
        raise ValueError("Base64 field is too long")
    try:
        raw = base64.b64decode(text, validate=True)
    except (binascii.Error, ValueError) as exc:
        raise ValueError("invalid standard Base64 field") from exc
    if len(raw) > MAX_BYTES:
        raise ValueError("decoded field exceeds 256 bytes")
    if base64.b64encode(raw).decode("ascii") != text:
        raise ValueError("Base64 field is not canonical")
    return raw

The re-encoding comparison requires the exact spelling produced by the standard encoder. It also rejects surplus padding if a decoder accepts it. The helper returns bytes so downstream code can use the identifier’s binary representation directly. Non-ASCII strings become a field-level ValueError; callers supplying the wrong Python type receive TypeError.

Keep the Size Limit at Both Boundaries

The largest accepted value encodes to 344 characters. That character count also accommodates 257 or 258 decoded bytes, so a text-length check alone cannot enforce the 256-byte limit. The helper checks the decoded size as well.

Save this demonstration beside the helper:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import base64
from base64_field import parse_base64_field

print(parse_base64_field("Zg=="))
print(base64.b64decode("Zh==", validate=True))
for text in ["Zh==", base64.b64encode(b"x" * 257).decode("ascii")]:
    try:
        parse_base64_field(text)
    except ValueError:
        print("Rejected")
# b'f'
# b'f'
# Rejected
# Rejected

The first rejection catches an alternate spelling; the second catches an oversized value whose encoded length still fits. Checking length before decoding bounds the work performed by this helper. Apply request-body limits before parsing a large incoming document too: this function receives an already allocated string.

Test the Field’s Accepted Language

Save this as test_base64_field.py beside the helper and run python test_base64_field.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import base64
from base64_field import parse_base64_field

for raw in [b"", b"f", b"fo", b"foo", b"\xfb\xff", bytes(range(256))]:
    text = base64.b64encode(raw).decode("ascii")
    assert parse_base64_field(text) == raw

for text in [
    "Zg", "Zg=", "Zg===", "Zg==\n", " Zg==", "Z!g==",
    "Zh==", "Zm9=", "- /8=", "-_8=", "=Zg==", "Zg==AAAA",
    "\u00e9", base64.b64encode(b"x" * 257).decode("ascii"),
    base64.b64encode(b"x" * 259).decode("ascii"),
]:
    try:
        parse_base64_field(text)
    except ValueError:
        pass
    else:
        raise AssertionError(f"invalid field accepted: {text!r}")

for value in [None, 0, True, b"Zg=="]:
    try:
        parse_base64_field(value)
    except TypeError:
        pass
    else:
        raise AssertionError(f"non-string field accepted: {value!r}")

print("Canonical Base64 checks passed.")

The valid samples cover empty input, each remainder modulo three, the standard alphabet’s + and / symbols, and the maximum size. The invalid samples distinguish missing padding, extra characters, unused-bit changes, another alphabet, and both size checks. Zm9= decodes to the same bytes as canonical Zm8=; this exercises the two-byte final group.

Keep Encoding Rules Separate from Record Policy

This field deliberately rejects URL-safe Base64, data URL prefixes, and MIME line wrapping. If a different field needs one of those formats, define its own contract and tests. Automatically trying several decoders would make this field’s accepted format harder to reason about.

After parsing, check any record-specific rules, such as a fixed identifier length or whether empty bytes are allowed. Successful parsing establishes an encoding and a size bound; it does not authenticate the record or establish that an identifier exists. Store the returned bytes, or re-encode them when a text column needs the same canonical spelling.