Base64 vs Base64url: Padding, Validation and Canonical Input
Diagnose Base64 and Base64url alphabet, padding and decoding errors. Build explicit Python validators and reproduce 853 checks, including noncanonical pad bits.
Choose the alphabet and padding policy from the field’s protocol. Base64url replaces + and / with - and _, but URL-safe encoders do not all omit padding. Decoder acceptance is also broader than canonical validation: check syntax, decode bytes and compare an exact re-encoding when the contract requires one spelling.
Choose an encoding contract before fixing the decoder
An API rejects a value with “incorrect padding.” Another decoder accepts the same value after punctuation is inserted. A token copied from a URL contains underscores instead of slashes. These failures often begin with an unspecified input contract: the producer and consumer disagree about which spelling is allowed.
Base64 represents bytes as printable characters. Standard Base64 and Base64url use different characters at two alphabet positions. Padding is another decision, and it is not determined simply by seeing “URL” in an encoding name. The surrounding protocol must say whether padding is required or omitted and whether whitespace is acceptable.
This guide implements two deliberately narrow example profiles: canonical standard Base64 with required padding when needed, and canonical unpadded Base64url. They are useful for learning how to enforce a field contract. They are not a universal decoder for MIME, data URLs, JWTs or every application that happens to use Base64.
| Property | Standard padded profile | URL unpadded profile |
|---|---|---|
| Alphabet positions 62 and 63 | + and / | - and _ |
| Padding when final group needs it | One or two trailing = characters | No = characters |
| Whitespace in this example | Rejected | Rejected |
| Empty string in this example | Accepted as empty bytes | Accepted as empty bytes |
| Output of decoding | Bytes | Bytes |
Source: RFC 4648: alphabets, padding and canonical pad bits ↗
Follow the bytes through the final group
Three input bytes form 24 bits, which divide into four six-bit values. Each value selects one alphabet character. When only one or two input bytes remain, the final group has unused bits. Standard padded output fills the character group with equals signs; the unused bits in its alphabet symbols must be zero for a canonical encoding.
For the byte f, the standard spelling is Zg== and our unpadded URL spelling is Zg. For fo, they are Zm8= and Zm8. For foo, both are Zm9v. These examples also show why a string consisting only of letters and digits does not reveal which alphabet its producer intended.
To expose the alphabet difference, use the invented two-byte value fb ff in hexadecimal. Its standard form is +/8=; its unpadded URL form is -_8. This is a more informative integration fixture than encoding an English greeting, because it exercises both distinguishing characters and a short final group.
Under an unpadded contract, a length remainder of one modulo four cannot represent a valid complete encoding. Remainders of two or three can be padded internally for decoding, after the original spelling has passed the profile’s grammar. Appending equals signs blindly does not repair mixed alphabets, punctuation or a truncated value.
Source: RFC 4648: alphabets, padding and canonical pad bits ↗
Separate decoder acceptance from canonical spelling
Python 3.12 base64.b64decode defaults to validate=False. Its documented behavior discards characters outside the accepted alphabet before checking padding. That can be useful for compatibility, but it makes the function’s success an insufficient validator for a tightly specified application field. With validate=True, non-alphabet characters cause an error.
Even that stricter switch does not enforce every canonicality decision in our profiles. The lab verifies that Python 3.12.14 accepts Zh== with validate=True and returns the same byte f as Zg==. The former has nonzero unused pad bits. A successful byte result therefore cannot establish that the submitted spelling was the canonical one.
Our extra check encodes the decoded bytes again using the selected profile, then compares the generated string with the original input exactly. For this contract, a mismatch is rejected. We do not silently normalize the input and label it valid, because that would erase the distinction the caller wanted to enforce.
Canonicality is a representation rule, not proof of authenticity. An attacker can generate perfectly canonical encoded bytes. Likewise, do not rewrite a signed token or protected message before signature verification unless its protocol explicitly requires that transformation. Keep the original serialized value for the protocol implementation that owns verification.
Runtime defaults are not interchangeable validation rules
Node.js Buffer decoding deliberately accepts more than one alphabet: its base64 mode accepts the URL-safe alphabet and ignores whitespace, while base64url mode also accepts regular Base64. When encoding, Node’s base64url mode omits padding. This documented interoperability behavior is useful, but it does not enforce an alphabet-exclusive input contract.
Python’s urlsafe_b64encode, by contrast, can return trailing equals signs. Calling an encoder “URL-safe” is therefore not enough to predict its output’s padding. Record a concrete expected string in your integration test and specify the transformation required by the receiving protocol. Avoid assuming that equivalent API names across languages imply identical acceptance rules.
For JWS, the specification defines Base64url with trailing padding removed. That is a property of that protocol’s serialization. Decoding one segment for inspection still does not verify the JWS signature, validate application claims or establish that the sender should be trusted. Use a maintained protocol library for those tasks.
A bounded validator with two explicit profiles
The function below takes a string and a profile name. It rejects unsupported profiles, oversized inputs and syntax that does not match the chosen alphabet or padding rule. Empty strings are accepted as an encoding primitive; an application requiring a nonempty identifier must add that separate requirement.
For the standard profile, the grammar permits complete four-character groups and only the appropriate short final groups. For the URL profile, it rejects equals signs, standard-only symbols and impossible lengths. It adds temporary padding only after these checks, then uses the validating Python decoder and the exact re-encoding comparison.
The 4,096-character limit is an example field budget. At the accepted all-A boundary in the fixture, it decodes to 3,072 bytes. A server should also bound the request before constructing a large string; this helper is not a network-body limiter, streaming decoder or general resource-isolation mechanism. Choose limits based on the actual field and transport.
Save the complete listing as base64_lab.py and run python3 base64_lab.py. It uses the standard library, performs no network requests, and prints its Python version and check count. The reusable decoder is at the top; the rest of the listing is the executable fixture, including an independent bit-string encoder.
import base64
import binascii
import random
import re
import sys
MAX_ENCODED = 4096
STD = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
URL = STD[:62] + '-_'
def decode_canonical(text, profile):
if profile not in ('standard-padded', 'url-unpadded'):
raise ValueError('unknown profile')
if not isinstance(text, str) or len(text) > MAX_ENCODED:
raise ValueError('expected a string of at most 4096 characters')
if profile == 'standard-padded':
grammar = r'(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?'
if re.fullmatch(grammar, text) is None:
raise ValueError('invalid standard-padded syntax')
padded, altchars = text, None
else:
if re.fullmatch(r'[A-Za-z0-9_-]*', text) is None or len(text) % 4 == 1:
raise ValueError('invalid url-unpadded syntax')
padded, altchars = text + '=' * (-len(text) % 4), b'-_'
try:
raw = base64.b64decode(padded, altchars=altchars, validate=True)
except binascii.Error as error:
raise ValueError('invalid encoded data') from error
canonical = (base64.b64encode(raw).decode('ascii')
if profile == 'standard-padded'
else base64.urlsafe_b64encode(raw).decode('ascii').rstrip('='))
if canonical != text:
raise ValueError('noncanonical spelling or nonzero pad bits')
return raw
# Independent bit-string encoder: no base64 calls.
def reference_encode(raw, alphabet, padded):
bits = ''.join(format(byte, '08b') for byte in raw)
bits += '0' * (-len(bits) % 6)
text = ''.join(alphabet[int(bits[i:i + 6], 2)]
for i in range(0, len(bits), 6))
return text + '=' * (-len(text) % 4) if padded else text
checks = 0
def check(value, label):
global checks
if not value:
raise AssertionError(label)
checks += 1
def rejects(text, profile):
try:
decode_canonical(text, profile)
except ValueError:
check(True, 'rejected malformed/noncanonical input')
else:
raise AssertionError(repr(text) + ' unexpectedly accepted')
vectors = [('', ''), ('f', 'Zg=='), ('fo', 'Zm8='), ('foo', 'Zm9v'),
('foob', 'Zm9vYg=='), ('fooba', 'Zm9vYmE='), ('foobar', 'Zm9vYmFy')]
for plain, encoded in vectors:
check(decode_canonical(encoded, 'standard-padded') == plain.encode(), 'RFC vector decode')
check(reference_encode(plain.encode(), STD, True) == encoded, 'RFC vector encode')
rng = random.Random(70)
for i in range(201):
raw = bytes(rng.randrange(256) for _ in range(i % 129))
for profile, alphabet, padded in [('standard-padded', STD, True),
('url-unpadded', URL, False)]:
expected = reference_encode(raw, alphabet, padded)
actual = (base64.b64encode(raw).decode('ascii') if padded
else base64.urlsafe_b64encode(raw).decode('ascii').rstrip('='))
check(actual == expected, 'independent encoder agreement')
check(decode_canonical(expected, profile) == raw, 'round trip')
for text in ['Zg', 'Zg=', 'Zg===', '=Zg==', 'Z=g=', 'Zg==x', 'Zg==\n',
' Zg==', 'Zg!!==', '-_8=', 'Zh==', 'Zm9=', 'é', 'A', 'A' * 4100]:
rejects(text, 'standard-padded')
for text in ['Zg==', '+/8', '-_8=', 'Z g', 'Zg\n', 'Zg!', 'Zh', 'Zm9',
'é', 'A', 'A' * 4097]:
rejects(text, 'url-unpadded')
check(base64.b64decode('Zh==', validate=True) == b'f', 'validate is not pad-bit canonicality')
check(base64.b64decode('Zg!!==') == b'f', 'default decoder discards punctuation')
check(decode_canonical('+/8=', 'standard-padded') == b'\xfb\xff', 'standard distinguishing alphabet')
check(decode_canonical('-_8', 'url-unpadded') == b'\xfb\xff', 'URL distinguishing alphabet')
text = 'café / بيانات'
encoded = base64.urlsafe_b64encode(text.encode('utf-8')).decode().rstrip('=')
check(decode_canonical(encoded, 'url-unpadded').decode('utf-8') == text, 'explicit UTF-8 round trip')
raw = decode_canonical('/w==', 'standard-padded')
check(raw == b'\xff', 'valid binary need not be text')
try:
raw.decode('utf-8')
except UnicodeDecodeError:
check(True, 'UTF-8 failure is separate from Base64 validity')
else:
raise AssertionError('invalid UTF-8 accepted')
check(len(decode_canonical('A' * 4096, 'url-unpadded')) == 3072, 'accepted encoded size boundary')
rejects('Zg==', 'unknown-profile')
print(f'PASS: {checks} checks; Python {sys.version.split()[0]}')
What the fixture verifies
The published listing passed 853 checks on Python 3.12.14. Seven fixed text/encoding pairs check known outputs and decoding. Another 201 deterministic byte arrays cover lengths from zero through 128 and repeat some lengths with different values. For each array, both profiles are compared with an independently written bit-string encoder, then decoded back to the original bytes.
The negative examples are selected to distinguish policies: missing or extra padding, an equals sign inside the data, leading and trailing whitespace, punctuation, the wrong alphabet, non-ASCII text, an impossible length and nonzero pad bits. The fixture also tests both sides of the encoded-size boundary and an unsupported profile name.
Two explicit compatibility checks document the Python defaults being discussed, rather than merely assuming them. Additional cases exercise the distinguishing alphabet bytes, a UTF-8 text round trip, and valid Base64 whose decoded byte ff is not valid UTF-8. These checks separate representation validity from the interpretation of the resulting bytes.
This is sampled and deliberately bounded coverage. It is not an exhaustive proof over every input string, a browser compatibility result, or a benchmark. The independent encoder reduces the chance that our expected valid output merely repeats the same library call as the implementation, while fixed malformed cases exercise the rejection paths.
Diagnose the layer that changed the value
When an encoded value changes in transit, compare the exact serialized input at the producer and consumer using invented fixtures. A plus sign transformed into a space may indicate form or query parsing, while a trailing newline may come from a file or command-line workflow. Do not remove arbitrary characters just to make a decoder return bytes; identify the transport rule first.
When decoding succeeds but text looks corrupted, inspect the bytes before changing Base64 settings. Text must first be encoded into bytes using an agreed character encoding, such as UTF-8, and decoded back using the same rule. Binary image or compressed data should remain bytes until the relevant format parser handles it.
When a system needs a stable textual identifier, decide whether equality means identical encoded strings or identical decoded bytes. Our canonical profiles make that choice explicit by accepting one spelling per byte sequence within each profile. Apply the decision consistently at the field boundary, rather than letting separate services make different guesses.
Finally, treat Base64 as a representation, not a secret-keeping mechanism. Use test values when collecting evidence, and avoid pasting real credentials into public decoding tools. A reliable repair starts with the field’s alphabet, padding and text rules, then checks the actual bytes. That is more precise than treating every decoding error as missing equals signs.
Source: RFC 7515: JWS Base64url definition and serialization ↗
Your next steps
- Specify alphabet, padding, whitespace, size and empty-value rules for the field.
- Keep decoded bytes separate from UTF-8 text and protocol-level authenticity checks.
- Test distinguishing alphabet bytes and malformed final groups, not only an English greeting.
Sources & official resources
Linked resources checked on 2026-11-01. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →