问题
为什么 Shell 中的 echo 'abc' | base64
和 Python 中的结果不一样?
原因
Shell 的 echo
命令默认会在输出末尾添加换行符 \n
,这个换行符也会被 base64 编码。
解决方法
Shell 中不添加换行符
使用 echo -n
选项:
Python 中不添加换行符
1 2 3 4 5
| import base64
data = 'abc' encoded_data = base64.b64encode(data.encode('utf-8')) print(encoded_data.decode('utf-8'))
|
现在两者结果一致!
Python 中添加换行符(模拟默认 echo)
1 2 3 4 5
| import base64
data = 'abc\n' encoded_data = base64.b64encode(data.encode('utf-8')) print(encoded_data.decode('utf-8'))
|
Python Base64 常用方法
标准编码/解码
1 2 3 4 5 6 7 8 9 10 11 12 13
| import base64
data = "Python Base64 编码测试!"
data_bytes = data.encode('utf-8') encoded_data = base64.b64encode(data_bytes) print("编码后:", encoded_data)
decoded_data = base64.b64decode(encoded_data) print("解码后:", decoded_data.decode('utf-8'))
|
URL 安全编码/解码
将 +
和 /
替换为 -
和 _
,适用于 URL 参数:
1 2 3 4 5 6 7
| urlsafe_encoded = base64.urlsafe_b64encode(data_bytes) print("URL安全编码:", urlsafe_encoded)
urlsafe_decoded = base64.urlsafe_b64decode(urlsafe_encoded) print("URL安全解码:", urlsafe_decoded.decode('utf-8'))
|
常用方法对比
方法 |
说明 |
b64encode(s) |
标准 Base64 编码 |
b64decode(s) |
标准 Base64 解码 |
urlsafe_b64encode(s) |
URL 安全编码(替换 +/) |
urlsafe_b64decode(s) |
URL 安全解码 |
注意事项
- Base64 是编码方式,不是加密方法
- 不应该用于保护敏感信息
- Shell 和 Python 编码差异主要源于换行符