我有一些 base64 编码的数据,即使其中存在填充错误,我也想将其转换回二进制。如果我使用
base64.decodestring(b64_string)
它会引发“不正确的填充”错误。还有其他方法吗?
更新:感谢所有反馈。老实说,所有提到的方法听起来都有些打击
错过了所以我决定尝试openssl。以下命令有效:
openssl enc -d -base64 -in b64string -out binary_data
最佳答案
正如在其他回复中所说,base64 数据可能会以多种方式被破坏。
但是,如 Wikipedia说,删除填充(base64 编码数据末尾的 '=' 字符)是“无损的”:
From a theoretical point of view, the padding character is not needed, since the number of missing bytes can be calculated from the number of Base64 digits.
因此,如果这确实是您的 base64 数据唯一“错误”的地方,则可以重新添加填充。我想出了这个能够解析 WeasyPrint 中的“数据” URL,其中一些是 base64 没有填充:
import base64
import re
def decode_base64(data, altchars=b'+/'):
"""Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
"""
data = re.sub(rb'[^a-zA-Z0-9%s]+' % altchars, b'', data) # normalize
missing_padding = len(data) % 4
if missing_padding:
data += b'='* (4 - missing_padding)
return base64.b64decode(data, altchars)
此功能的测试:weasyprint/tests/test_css.py#L68
关于Python:base64解码时忽略 'Incorrect padding'错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67172073/