的Python:忽略“填充不正确”的错误时的base64解码 [英] Python: Ignore 'Incorrect padding' error when base64 decoding

查看:357
本文介绍了的Python:忽略“填充不正确”的错误时的base64解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据,是连接的base64 codeD,我要回二进制转换,即使在它里面的填充错误。如果我用

  base64.de codeString的(b64_string)

它提出了一个填充不正确的错误。有另一种方式?

更新:感谢所有的反馈。说实话,提到的所有方法听起来有点命中
而错过,所以我决定尝试OpenSSL的。下面的命令工作一种享受:

  OpenSSL的ENC -d -base64 -in b64string退房手续binary_data


解决方案

正如在其他答复说,有其中的base64数据可能被破坏的各种方式。

不过,由于维基百科说,去除填充(在'='字符连接的base64 codeD数据)的到底是无损:


  

从理论的角度来看,是不是需要填充字符,
  因为缺少的字节数可以从数计算
  Base64编码的位数。


因此​​,如果这真的是唯一的错误与您的base64数据,填充可以只加回。我想出了这个才能够解析数据,在WeasyPrint网址,其中一些是BASE64没有填充:

 高清德code_base64(数据):
    德code的base64,填充是可选的。    :参数数据:Base64编码数据作为ASCII字节串
    :返回:去codeD字节的字符串。    
    missing_padding = LEN(数据)4%
    如果missing_padding!= 0:
        数据+ = B'='*(4 - missing_padding)
    返回base64.de codeString的(数据)

此功能检查:<一href=\"https://github.com/Kozea/WeasyPrint/blob/c521322ee763d6f9f5791b6f26d69cbc61f2470d/weasyprint/tests/test_css.py#L68\"相对=nofollow> weasyprint /测试/ test_css.py#L68

I have some data that is base64 encoded that I want to convert back to binary even if there is a padding error in it. If I use

base64.decodestring(b64_string)

it raises an 'Incorrect padding' error. Is there another way?

UPDATE: Thanks for all the feedback. To be honest, all the methods mentioned sounded a bit hit and miss so I decided to try openssl. The following command worked a treat:

openssl enc -d -base64 -in b64string -out binary_data

解决方案

As said in other responses, there are various ways in which base64 data could be corrupted.

However, as Wikipedia says, removing the padding (the '=' characters at the end of base64 encoded data) is "lossless":

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.

So if this is really the only thing "wrong" with your base64 data, the padding can just be added back. I came up with this to be able to parse "data" URLs in WeasyPrint, some of which were base64 without padding:

def decode_base64(data):
    """Decode base64, padding being optional.

    :param data: Base64 data as an ASCII byte string
    :returns: The decoded byte string.

    """
    missing_padding = len(data) % 4
    if missing_padding != 0:
        data += b'='* (4 - missing_padding)
    return base64.decodestring(data)

Tests for this function: weasyprint/tests/test_css.py#L68

这篇关于的Python:忽略“填充不正确”的错误时的base64解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆