Base64 represents binary data using 64 printable characters. It is commonly used to transmit binary
data over text-based protocols, to embed resources in JSON/XML/HTML, and in HTTP Basic Auth.
The standard alphabet is AโZ aโz 0โ9 + /
with padding =
; the URL-safe variant
replaces + /
with - _
.
import base64
)b64encode(data: bytes, altchars: bytes | None = None) -> bytes
b64decode(data: bytes | str, altchars: bytes | None = None, validate: bool = False) -> bytes
standard_b64encode / standard_b64decode
(force the standard alphabet)urlsafe_b64encode / urlsafe_b64decode
(URL/filename-safe variant)b32encode / b32decode
, b16encode / b16decode
a85encode / a85decode
, b85encode / b85decode
(ASCII85/Base85)import base64
text = "Hello, world"
raw = text.encode("utf-8")
b64 = base64.b64encode(raw) # bytes
print(b64) # b'SGVsbG8sIHdvcmxk'
plain = base64.b64decode(b64)
print(plain.decode("utf-8")) # Hello, world
import base64
raw = b"token:id/123+scope"
url_b64 = base64.urlsafe_b64encode(raw)
print(url_b64) # b'dG9rZW46aWQvMTIzK3Njb3Bl'
print(base64.urlsafe_b64decode(url_b64)) # b'token:id/123+scope'
import base64, binascii
try:
base64.b64decode(b"@@invalid@@", validate=True)
except binascii.Error as exc:
print("Decode failed:", exc)
import base64
# Binary file โ Base64 text
with open("input.bin", "rb") as f:
encoded = base64.b64encode(f.read()).decode("ascii")
with open("output.txt", "w", encoding="ascii") as f:
f.write(encoded)
# Base64 text โ binary file
with open("output.txt", "r", encoding="ascii") as f:
data = base64.b64decode(f.read())
with open("restored.bin", "wb") as f:
f.write(data)
a85encode/a85decode
and b85encode/b85decode
provide higher density encodings (often used
in PostScript and PDF). They accept and return bytes
, with options for grouping and compression.
import base64
data = b"hello base85"
a85 = base64.a85encode(data)
b85 = base64.b85encode(data)
print(a85, b85)
print(base64.a85decode(a85))
print(base64.b85decode(b85))
Note: For complete details and edge cases, refer to the official docs at
https://docs.python.org/3/library/base64.html
.