Python:base64解码时忽略 'Incorrect padding'错误

标签 python base64

我有一些 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/

相关文章:

通过 IDLE 运行的 Python 脚本没有输出

android - encodeToString base64 安卓问题

python - 不同数量的条件

python - 使用 Python 在单独的线程中进行 GPSd 轮询

python - NumPy 数组的有效(非 NaN)部分的开始、停止索引切片

Java base64编码,解码产生不同的结果

java - "java.util.zip.DataFormatException: incorrect header check"在 JavaScript 中放气然后在 Java 中膨胀

php - 如何直接通过 PHP 将 Base64 字符串导出到服务器端的文件,而不将其保存在 Web 服务器中?

javascript - 如何将 base 64 编码为 .kml 文件?

python - 从Python中的不同目录导入同名文件?