Base64 in Python

게시

이 가이드에서

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.

다음으로 이 비공개 도구를 써 보세요

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.

자주 묻는 질문

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.

관련 도구 및 가이드

댓글 (0)

“Base64 in Python”에 대한 질문, 아이디어, 버그가 있으신가요? 댓글을 남기거나 도구를 평가하거나 다른 사람에게 답글을 달아 주세요.

아직 댓글이 없습니다. 첫 번째로 의견을 남겨 주세요!

댓글 남기기

이 도구 평가:
Esc
↑ ↓ 이동↵ 열기Esc 닫기