Developer Documentation
Python
Updated September 19, 2026

Base64 Encoding and Decoding in Python

Encode and decode Base64 safely, including UTF-8 text and binary data in Python.

Base64 converts binary data to printable ASCII text. It is useful for transport and embedding, but it is an encoding format, not encryption.

Quick Start#

The following example uses the standard Python API or a widely used package for this task.

Quick start#

Python
1import base6423text = "Hello ToolPorta 👋"4encoded = base64.b64encode(text.encode("utf-8")).decode("ascii")5decoded = base64.b64decode(encoded, validate=True).decode("utf-8")67print(encoded)8print(decoded)

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Binary files#

Python
1import base642from pathlib import Path34data = Path("input.bin").read_bytes()5encoded = base64.b64encode(data)6Path("input.b64").write_bytes(encoded)78restored = base64.b64decode(encoded, validate=True)9Path("restored.bin").write_bytes(restored)

Important Notes#

Use validate=True when accepting untrusted standard Base64 input and you want invalid alphabet characters rejected.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement Base64 in other languages: