Base64 in Python

Published

In this guide

Python’s base64 module works on bytes. Encode strings with .encode("utf-8") first; use urlsafe_b64encode for JWT-style values.

Watch padding and validate=True on decode to catch corrupt input early.

Cross-check results with the browser tools when debugging APIs or PEM data.

Try these private tools next

Python’s standard library module base64 covers standard Base64, Base64URL, Base32, Base16 and Ascii85. Its functions take and return bytes, which is the first thing to remember.

Encode a string

import base64

encoded = base64.b64encode("Grüße 👋".encode("utf-8"))
print(encoded)            # b'R3LDvMOfZSDwn5GL'
print(encoded.decode())   # 'R3LDvMOfZSDwn5GL'  (str)

Passing a str directly raises TypeError: a bytes-like object is required, not 'str'.

Decode to a string

text = base64.b64decode("R3LDvMOfZSDwn5GL").decode("utf-8")

b64decode accepts both str (ASCII only) and bytes.

Strict validation

By default b64decode silently discards characters outside the alphabet. Pass validate=True to reject them:

import binascii

try:
    data = base64.b64decode(value, validate=True)
except binascii.Error as e:
    print("Invalid Base64:", e)

“Incorrect padding” error

binascii.Error: Incorrect padding means the length is not a multiple of 4. This is common with Base64URL values from JWTs or URLs, which omit =. Restore the padding:

def b64decode_nopad(s: str) -> bytes:
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))

Base64URL

base64.urlsafe_b64encode(b"\xfb\xff").decode()   # '-_8='
base64.urlsafe_b64encode(data).rstrip(b"=")      # without padding

Files and images

from pathlib import Path

b64 = base64.b64encode(Path("logo.png").read_bytes()).decode()
data_uri = f"data:image/png;base64,{b64}"

Path("restored.png").write_bytes(base64.b64decode(b64))

For very large files use base64.encode(infile, outfile), which streams and wraps lines at 76 characters (MIME style).

Line breaks

b64encode never adds line breaks. base64.encodebytes() inserts a newline every 76 characters, as required by e-mail (MIME). b64decode ignores newlines only when validate=False.

Command line

python3 -m base64 file.bin        # encode
python3 -m base64 -d file.b64     # decode

Verify your output with the Base64 decoder or check the value with the validator.

Usein kysytyt kysymykset

bytes vs str in Python Base64?

Always Base64-encode bytes. Decode returns bytes — decode to str only when the payload is text.

How do I do Base64URL in Python?

Use base64.urlsafe_b64encode / urlsafe_b64decode and strip or restore padding as needed.

Aiheeseen liittyvät työkalut ja oppaat

Kommentit (0)

Kysymyksiä, ideoita tai bugi työkalussa “Base64 in Python”? Jätä kommentti, arvioi työkalu tai vastaa muille.

Ei vielä kommentteja. Ole ensimmäinen, joka jakaa palautteesi!

Jätä kommentti

Arvioi tämä työkalu:
Esc
↑ ↓ siirrä↵ avaaEsc sulje