Python Base64: encode, decode, and validate with examples
Copy runnable Python examples for UTF-8 text, bounded file reads, strict Base64 decoding, URL-safe values, and byte-for-byte round-trip checks.
Encode and decode UTF-8 text
Python’s standard-library base64 module needs no package installation. The examples below use Python 3.10 or newer and run locally without API keys or network requests. Encoding accepts bytes and returns ASCII bytes; decoding returns the original bytes. See the Python Base64 reference.
import base64
original = "Hello, 世界 👋"
encoded = base64.b64encode(original.encode("utf-8")).decode("ascii")
decoded_bytes = base64.b64decode(encoded, validate=True)
assert decoded_bytes.decode("utf-8") == original
print(encoded)
print(decoded_bytes.decode("utf-8"))
The ASCII conversion makes the encoded value suitable for a JSON string. The final UTF-8 conversion is for text only. Do not apply it to decoded PNG, MP3, ZIP, or arbitrary binary data.
Encode a file without an unbounded read
This self-contained example creates a small synthetic binary fixture in a temporary directory, then reads at most one byte beyond a 5 MiB limit. Replace the fixture path with your own local file in an application. The size cap is an example policy, not a Base64 standard or an API limit.
import base64
from pathlib import Path
from tempfile import TemporaryDirectory
LIMIT = 5 * 1024 * 1024
def encode_file(path):
with Path(path).open("rb") as source:
raw = source.read(LIMIT + 1)
if len(raw) > LIMIT:
raise ValueError("File exceeds the 5 MiB example limit")
return raw, base64.b64encode(raw).decode("ascii")
with TemporaryDirectory() as folder:
path = Path(folder) / "sample.bin"
path.write_bytes(bytes(range(256)))
original, encoded = encode_file(path)
restored = base64.b64decode(encoded, validate=True)
assert restored == original
print(f"Verified {len(restored)} bytes")
A round-trip comparison checks encoding correctness. It does not establish that an input file is safe to open. For larger files, prefer a supported binary upload or implement streaming with correctly aligned chunks rather than increasing memory limits blindly.
Reject malformed input and enforce a size limit
For an endpoint that requires canonical, padded, standard Base64, reject unexpected characters and compare the re-encoded result. This deliberately rejects whitespace, missing padding, and alternate spellings. It is stricter than some protocols require; do not use it unchanged for MIME or unpadded Base64URL.
import base64
import binascii
def decode_standard(value, max_bytes=1024):
if not isinstance(max_bytes, int) or max_bytes < 0:
raise ValueError("Invalid decoded-size limit")
if not isinstance(value, str) or not value.isascii():
raise ValueError("Expected an ASCII Base64 string")
if len(value) > 4 * ((max_bytes + 2) // 3):
raise ValueError("Encoded input is too large")
try:
raw = base64.b64decode(value, validate=True)
except (binascii.Error, ValueError) as error:
raise ValueError("Invalid Base64") from error
if len(raw) > max_bytes:
raise ValueError("Decoded input is too large")
if base64.b64encode(raw).decode("ascii") != value:
raise ValueError("Expected canonical padded Base64")
return raw
assert decode_standard("TQ==") == b"M"
assert decode_standard("") == b""
for invalid in ("TQ", "TQ==\n", "TR==", "TQ==$", "💬"):
try:
decode_standard(invalid)
except ValueError:
pass
else:
raise AssertionError(f"Accepted invalid input: {invalid!r}")
try:
decode_standard("TWE=", max_bytes=1)
except ValueError:
pass
else:
raise AssertionError("Decoded-size limit was not enforced")
print("Strict decoding checks passed")
Limit the HTTP request body before parsing JSON as well. A check inside a decoder cannot undo the memory already allocated for an oversized request.
Use Base64URL when the protocol requires it
For a protocol explicitly requiring unpadded Base64URL, remove padding when encoding, restore only the required padding when decoding, and validate the URL-safe alphabet. The re-encode check below also rejects nonzero unused bits.
import base64
import re
def decode_unpadded_url(value, max_bytes=1024):
if not isinstance(max_bytes, int) or max_bytes < 0:
raise ValueError("Invalid decoded-size limit")
if not isinstance(value, str) or len(value) > 4 * ((max_bytes + 2) // 3):
raise ValueError("Invalid or oversized input")
if not re.fullmatch(r"[A-Za-z0-9_-]*", value) or len(value) % 4 == 1:
raise ValueError("Invalid unpadded Base64URL")
padded = value + "=" * (-len(value) % 4)
raw = base64.b64decode(padded, altchars=b"-_", validate=True)
canonical = base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
if len(raw) > max_bytes or canonical != value:
raise ValueError("Noncanonical or oversized input")
return raw
original = b"\xfb\xff"
encoded = base64.urlsafe_b64encode(original).decode("ascii").rstrip("=")
assert encoded == "-_8"
assert decode_unpadded_url(encoded) == original
for invalid in ("+ /8=", "-_8=", "A", "-_9"):
try:
decode_unpadded_url(invalid)
except ValueError:
pass
else:
raise AssertionError("Accepted invalid Base64URL")
print(encoded)
Decoding a token is not signature verification or authentication. A readable JWT payload is not evidence that its claims are trustworthy.
Keep Data URLs and JSON serialization separate
Raw Base64, a Data URL, and an SDK byte parameter are different input types. The following creates a local JSON demonstration with a text Data URL. It is not a provider-specific request schema.
import base64
import json
raw = "Hello".encode("utf-8")
encoded = base64.b64encode(raw).decode("ascii")
data_url = "data:text/plain;charset=utf-8;base64," + encoded
payload = json.dumps({"data_url": data_url})
received = json.loads(payload)["data_url"]
header, body = received.split(",", 1)
assert header == "data:text/plain;charset=utf-8;base64"
assert base64.b64decode(body, validate=True) == raw
print("JSON round trip verified")
For untrusted Data URLs, also allowlist the media type, require the Base64 marker, and cap input length before decoding. Changing a MIME label does not convert the underlying file.
Try values in the local converter, read the bit-level explanation, or continue to AI speech and audio examples.