Skip to content

Base64 Encode / Decode — Python source

Encode text to Base64 or decode it back. UTF-8 safe, runs entirely in your browser, with a shareable link to your exact input.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""base64 — UTF-8 safe Base64 encode/decode.

Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `base64` tool, ported from
src/lib/base64.ts (the canonical TypeScript implementation).

Python 3 ``str`` is Unicode, so explicit ``.encode("utf-8")`` / ``.decode(
"utf-8")`` calls shuttle between text and the UTF-8 byte sequence that Base64
actually operates on — exactly the role TextEncoder / TextDecoder play in the
TypeScript original.

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import base64
import binascii
import re


def b64encode(text: str) -> str:
    """Encode a Unicode string to standard (padded) Base64.

    The string is first encoded to UTF-8 bytes so that characters outside
    Latin-1 (emoji, accents, CJK, ...) survive the round trip.
    """
    return base64.b64encode(text.encode("utf-8")).decode("ascii")


def b64decode(b64: str) -> str:
    """Decode a standard Base64 string back to the original Unicode text.

    Whitespace inside the input is stripped first (``\\s+`` mirrors the
    TypeScript port's regex), so line-wrapped Base64 decodes cleanly. Any
    malformed input — illegal characters, bad padding, or decoded bytes that
    are not valid UTF-8 — raises ``ValueError``, matching the TS port's
    "throw on invalid input" contract.

    Raises:
        ValueError: if the input is not valid Base64, or its decoded bytes
            are not valid UTF-8.
    """
    cleaned = re.sub(r"\s+", "", b64)

    try:
        # validate=True rejects characters outside the Base64 alphabet rather
        # than silently dropping them.
        raw = base64.b64decode(cleaned, validate=True)
    except (binascii.Error, ValueError) as exc:
        raise ValueError(f"invalid Base64 input: {exc}") from exc

    try:
        return raw.decode("utf-8")
    except UnicodeDecodeError as exc:
        raise ValueError(f"decoded bytes are not valid UTF-8: {exc}") from exc

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →