Base64 in Python

Diterbitkan

Dalam panduan ini

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.

Coba alat privat ini berikutnya

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.

Pertanyaan yang sering diajukan

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.

Alat dan panduan terkait

Komentar (0)

Ada pertanyaan, ide, atau bug di “Base64 in Python”? Tinggalkan komentar, beri rating alat ini, atau balas komentar lainnya.

Belum ada komentar. Jadilah yang pertama memberikan masukan!

Tinggalkan komentar

Beri rating alat ini:
Esc
↑ ↓ pindah↵ bukaEsc tutup