2017-05-24 226 views
1

我想为Base64使用Python的base64.b64decode解码字串(成字节)(STR)方法:Base64编码解码:特定的字符串不正确的填充(使用正确的填充)

46oWrWpy2gTEGwNnN6Ayy

和我确保它具有4 =的用于填充或出无奈任何这些的倍数:

46oWrWpy2gTEGwNnN6Ayy =

46oWrWpy2gTEGwNnN6Ayy ==

46oWrWpy2gTEGwNnN6Ayy ===

46oWrWpy2gTEGwNnN6Ayy ================================ ==================

但我仍然在Python v3.6.1上得到“不正确的填充”。其他字符串很好。

我向同事展示,他尝试使用Python 2并观察相同的响应。

我注意到删除第一个“4”足以确保Base64解码工作。

我已阅读了Python's docs(注意casefold不适用于base64)并且还没有进一步冒险进入RFC3548,但想知道其他人是否遇到过类似的事情。任何人有任何线索:)?当然,这不可能是Python的Base64解码器中的一个错误?

回答

2

曾为它出。

Base64文本的每个字符都是原始8位的6位。如果一个字符在原始字节的中间,那么你缺少一些剩余的位。维基百科文章(和许多在线答案)似乎使用填充作为可替换的'0'字节,而不是这种情况(在Base64字典中它应该被编码为A)。

由于缺少数据,填充不可互换。

#!/usr/bin/env python3 

# We use hexlify for debugging. 
import binascii 

# We use the Base64 library. 
import base64 

# Base64 works on multiples of 4 characters.. 
# ..Sometimes we get 3/2/1 characters and it might be midway through another. 
def relaxed_decode_base64(data): 

# If there is already padding we strim it as we calculate padding ourselves. 
if '=' in data: 
    data = data[:data.index('=')] 

# We need to add padding, how many bytes are missing. 
missing_padding = len(data) % 4 

# We would be mid-way through a byte. 
if missing_padding == 1: 
    data += 'A==' 
# Jut add on the correct length of padding. 
elif missing_padding == 2: 
    data += '==' 
elif missing_padding == 3: 
    data += '=' 

# Actually perform the Base64 decode. 
return base64.b64decode(data) 

# Debugging 
print(str(relaxed_decode_base64('46oWrWpy2gTEGwNnN6Ayy')) + '\n') 

testString = '' 

for count in range(0, 1024): 
testString += '/' 
print(str(len(testString)) + ' - ' + testString) 
print(binascii.hexlify(relaxed_decode_base64(testString))) 
input() 
0

似乎是在你的数据有问题,没有涉及到的Python:

$ echo 46oWrWpy2gTEGwNnN6Ayy | base64 -d 
㪭jrÚÄg7 2base64: invalid input 
$ echo 46oWrWpy2gTEGwNnN6Ayy= | base64 -d 
㪭jrÚÄg7 2base64: invalid input 
$ echo 46oWrWpy2gTEGwNnN6Ayy== | base64 -d 
㪭jrÚÄg7 2base64: invalid input 
$ echo 46oWrWpy2gTEGwNnN6Ayy=== | base64 -d 
㪭jrÚÄg7 2base64: invalid input 
$ echo 46oWrWpy2gTEGwNnN6Ayy==== | base64 -d 
㪭jrÚÄg7 2base64: invalid input 

我设法给它这种解码方式(除去最后的 'Y'):

$ echo 46oWrWpy2gTEGwNnN6Ay | base64 -d 
㪭jrÚÄg7 2