[英]Base64 Decode : Specific String Incorrect Padding (with correct padding)
我正在嘗試使用Python的base64.b64decode(str)方法對Base64解碼字符串(轉換為字節):
46oWrWpy2gTEGwNnN6Ayy
並且我確保它具有4的倍數用於填充或出於以下原因而感到沮喪:
46oWrWpy2gTEGwNnN6Ayy =
46oWrWpy2gTEGwNnN6Ayy ==
46oWrWpy2gTEGwNnN6Ayy ===
46oWrWpy2gTEGwNnN6Ayy ================================================= =
但是在Python v3.6.1上仍然出現“錯誤填充”。 其他字符串也可以。
我向一位同事展示了他嘗試使用Python 2並觀察到了相同的響應。
我注意到刪除第一個“ 4”足以確保Base64解碼正常工作。
我已經略讀了Python的文檔 (注意casefold不適用於Base64),並且還沒有進一步冒險使用RFC3548,但是想知道以前是否有人遇到過類似的情況。 任何人都有任何線索:)? 當然這不是Python的Base64解碼器中的錯誤嗎?
解決了。
Base64文本的每個字符是原始8位中的6位。 如果某個字符位於原始字節的中間,則您會丟失一些剩余的位。 Wikipedia文章(以及許多在線答案)似乎將填充與“ 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()
似乎是您數據中的問題,與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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.