解码python base64字符串

时间:2012-07-25 18:21:17

标签: python base64 decode

我已经提取了图像的forecolor,texture和edgemap值的base64字符串,我有一个包含以下结构的列表:

forecolor=AgCEAg4DUQQCBQQGARMBFQE1AmUB
edge=AfCAFg5iIATCPwTAEIiBFggBDw
forecolor=AgAsAQ0CJAMcDRgOGg8DHQYeBzYBPQ4-DU0ETgNtBm4CfQI

我正在尝试解码这些值,但是我收到错误的填充错误,这是确切的错误:

Traceback (most recent call last):
  File "ImageVectorData.py", line 44, in <module>
    print "Decoded String: " + decoded.decode('base64', 'strict')
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/base64_codec.py", line 42, in base64_decode
    output = base64.decodestring(input)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/base64.py", line 321, in decodestring
    return binascii.a2b_base64(s)
binascii.Error: Incorrect padding

这是我的代码:

for item in value:
    print "String before Split: " + item
    if item.split("=")[0] == "forecolor":
        decoded = (item.split("=")[1])
        print "String to be decoded: " + decoded
        print "Decoded String: " + decoded.decode('base64', 'strict')

当第一个forecolor base64字符串被解码时,我也看到了一个有趣的输出: 以下是其中的概述:

String before Split: forecolor=AgCEAg4DUQQCBQQGARMBFQE1AmUB
String to be decoded: AgCEAg4DUQQCBQQGARMBFQE1AmUB
Decoded String: ?Q5e

我不确定我在这里做错了什么。我查看了下面的python文档并尝试了但是这也不起作用: http://docs.python.org/library/base64.html

1 个答案:

答案 0 :(得分:8)

您正在尝试解码没有填充的Base64字符串。尽管Base64的许多版本都没有填充,但Python需要填充以进行标准的base64解码。此StackOverflow问题有一个更深入的解释:Python: Ignore 'Incorrect padding' error when base64 decoding

对于您的代码,我会进行类似于以下的修改:

for item in value:
    print "String before Split: " + item
    if item.split("=")[0] == "forecolor":
        decoded = (item.split("=")[1])
        print "String to be decoded: " + decoded
        # Add Padding if needed
        decoded += "===" # Add extra padding if needed
        print "Decoded String: " + decoded.decode('base64', 'strict')

根据您的评论,您似乎还需要将从base64解码返回的字节数组转换为整数列表。我假设整数是小尾数的短整数。

import struct
x = "AgAsAQ0CJAMcDRgOGg8DHQYeBzYBPQ4-DU0ETgNtBm4CfQI"
x += "==="
y = x.decode('base64', 'strict')
intList = [struct.unpack('<h', y[i] + y[i+1]) for i in xrange(0, len(y), 2)]
print intList

结果是:

[(2,), (300,), (525,), (804,), (3356,), (3608,), (3866,), (7427,), (7686,), (13831,), (15617,), (782,), (16723,), (-32749,), (16859,), (-32613,), (16543,)]