Python Base64 编码与解码:标准 Base64 和 URL 安全编码
Python 标准库中的 base64 模块提供了对 Base64 编码和解码的支持。该模块提供了以下函数:
b64encode(s, altchars=None): 将输入的字节串进行 Base64 编码,返回一个字节对象。可选参数altchars可以指定可替换的编码字符。b64decode(s, altchars=None, validate=False): 将输入的 Base64 编码的字节串或 ASCII 字符串进行解码,返回一个字节对象。可选参数altchars用于指定可替换的编码字符,validate参数用于是否进行编码字符校验。standard_b64encode(s): 使用标准的 Base64 编码字符集进行编码。standard_b64decode(s): 使用标准的 Base64 编码字符集进行解码。urlsafe_b64encode(s): 使用 URL 和文件系统安全的 Base64 编码字符集进行编码,可替换的编码字符为 '-' 和 '_'.urlsafe_b64decode(s): 使用 URL 和文件系统安全的 Base64 编码字符集进行解码,可替换的编码字符为 '-' 和 '_'.
以下是对每个函数的详细解释:
b64encode(s, altchars=None):
s: 要编码的字节串。altchars: 可选参数,指定可替换的编码字符。它应该是一个长度为 2 的字节串。例如,如果要将 '+' 和 '/' 替换为 '-' 和 '_', 则可以将altchars设置为b'-_'。
b64decode(s, altchars=None, validate=False):
s: 要解码的 Base64 编码的字节串或 ASCII 字符串。altchars: 可选参数,指定可替换的编码字符。它应该是一个长度为 2 的字节串或 ASCII 字符串。validate: 可选参数,指定是否进行编码字符校验。如果为True, 则在解码时会检查输入字符串是否符合 Base64 编码规范。如果为False, 则会忽略非 Base64 编码字符。
standard_b64encode(s) 和 standard_b64decode(s):
这两个函数使用标准的 Base64 编码字符集进行编码和解码,它们实际上是 b64encode 和 b64decode 的简化版本。
urlsafe_b64encode(s) 和 urlsafe_b64decode(s):
这两个函数使用 URL 和文件系统安全的 Base64 编码字符集进行编码和解码。它们使用 '-' 替代 '+' 和 '_' 替代 '/',以避免在 URL 或文件名中出现特殊字符。
示例:
import base64
# 使用标准 Base64 编码
message = b'Hello, world!'
encoded = base64.b64encode(message)
print(encoded) # 输出: b'SGVsbG8sIHdvcmxkIQ=='
decorded = base64.b64decode(encoded)
print(decorded) # 输出: b'Hello, world!'
# 使用 URL 安全 Base64 编码
message = b'Hello, world!'
encoded = base64.urlsafe_b64encode(message)
print(encoded) # 输出: b'SGVsbG8sIHdvcmxkIQ=='
decorded = base64.urlsafe_b64decode(encoded)
print(decorded) # 输出: b'Hello, world!'
原文地址: https://www.cveoy.top/t/topic/ofTM 著作权归作者所有。请勿转载和采集!