Python base64
库详解
base64 是一种将二进制数据编码为 ASCII 字符串 的方法,常用于在文本协议(如 HTTP、JSON)中安全传输二进制数据(如图片、文件)。Python 的 base64
模块提供了多种 Base64 变体的编解码功能。
核心功能
- 二进制 ↔ ASCII 互转:将二进制数据编码为可打印字符串,或反向解码。
- URL/文件名安全:使用
urlsafe_b64encode
替代+
和/
为-
和_
。 - 填充处理:支持保留或去除 Base64 字符串末尾的
=
填充符。 - 多标准支持:支持 Base16(hex)、Base32、Base64 等编码。
常用方法
1. 标准 Base64 编解码
方法 | 说明 | 参数 | 返回值 |
---|---|---|---|
b64encode(data) | 二进制数据 → Base64 字符串 | data: bytes | bytes (编码结果) |
b64decode(data) | Base64 字符串 → 二进制 | data: bytes/str | bytes (解码结果) |
示例:
python
import base64
# 编码
binary_data = b"Hello, World!"
encoded = base64.b64encode(binary_data) # b'SGVsbG8sIFdvcmxkIQ=='
print(encoded.decode('utf-8')) # 输出字符串:SGVsbG8sIFdvcmxkIQ==
# 解码
decoded = base64.b64decode(encoded)
print(decoded) # b'Hello, World!'
2. URL安全的 Base64 编解码
方法 | 说明 |
---|---|
urlsafe_b64encode(data) | 将 + 替换为 - ,/ 替换为 _ |
urlsafe_b64decode(data) | 反向解码 URL 安全的 Base64 字符串 |
示例:
python
encoded_urlsafe = base64.urlsafe_b64encode(b"data+with/slash") # b'ZGF0YSt3aXRoL3NsYXNo'
decoded_urlsafe = base64.urlsafe_b64decode(encoded_urlsafe) # b'data+with/slash'
3. 去除填充符 =
python
# 编码时去除填充符
encoded_no_pad = base64.b64encode(b"test").rstrip(b"=") # b'dGVzdA'
# 解码时补充填充符(Base64 长度需为 4 的倍数)
data = base64.b64decode(encoded_no_pad + b"=" * (-len(encoded_no_pad) % 4))
4. Base32 编解码
python
encoded_b32 = base64.b32encode(b"binary") # b'NBSWY3DP'
decoded_b32 = base64.b32decode(encoded_b32) # b'binary'
5. Base16(Hex)编解码
python
encoded_b16 = base64.b16encode(b"hello") # b'68656C6C6F'
decoded_b16 = base64.b16decode(encoded_b16) # b'hello'
常见应用场景
1. 图片转 Base64 嵌入网页
python
with open("image.png", "rb") as f:
img_base64 = base64.b64encode(f.read()).decode('utf-8')
html = f'<img src="data:image/png;base64,{img_base64}">'
2. 加密数据存储
python
import json
data = {"key": "secret_data".encode()}
encoded_data = base64.b64encode(data["key"]).decode('utf-8')
json.dump({"encrypted": encoded_data}, open("data.json", "w"))
3. 解码 API 返回的 Base64 数据
python
import requests
response = requests.get("https://api.example.com/data")
binary_data = base64.b64decode(response.json()["content"])
with open("file.zip", "wb") as f:
f.write(binary_data)
注意事项
-
输入数据类型:
- 编码方法(如
b64encode
)接受bytes
类型输入,字符串需先转换:str.encode('utf-8')
。 - 解码方法接受
bytes
或str
类型输入。
- 编码方法(如
-
填充符处理:
- Base64 字符串长度需为 4 的倍数,不足时需补
=
。 - 使用
rstrip(b"=")
可去除编码结果的填充符,但解码时需手动补充。
- Base64 字符串长度需为 4 的倍数,不足时需补
-
性能优化:
- 大文件建议分块编码(如每次读取 4096 字节)。
-
错误处理:
- 解码非法字符会抛出
binascii.Error
,可用try-except
捕获:python
try: base64.b64decode("invalid_data") except binascii.Error as e: print("解码失败:", e)
- 解码非法字符会抛出
通过掌握 base64
模块,可轻松实现二进制数据的安全文本化传输!