Python base64 模块

概览

Base64 使用 64 个可打印字符表示二进制数据,常用于基于文本的传输协议、在 JSON/XML/HTML 中内嵌资源, 以及 HTTP Basic 认证等场景。标准字母表为 A–Z a–z 0–9 + /,使用 = 作为填充; URL 安全变体用 - _ 替代 + /

主要 API(import base64

快速示例

字符串编码/解码(UTF-8)

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

URL 安全的 Base64

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)

文件 I/O

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)

ASCII85 / Base85

a85encode/a85decodeb85encode/b85decode 提供更高密度的编码(常见于 PostScript 与 PDF), 接收与返回的均为 bytes,并可配置分组与压缩等选项。

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))

提示:更多细节与边界情况请参考官方文档: https://docs.python.org/3/library/base64.html