Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

python - binascii.Error: Incorrect padding How to decode the end with /

I received a string encoded with base64, I am using python to decode it, but decoding failed, I found that the string is followed by / ends, I don't know how to decode it, I haven't found the answer, who can Help me

data = 'dXN1c19pZD0xMDg2P2RvY01kPTE3Mzc4JnR5cGU9bmV3/'

print(base64.urlsafe_b64decode(data))
print(base64.standard_b64decode(data))
print(base64.b64decode(data))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

data is a normal base64 encoded string, containing only characters from the base64 character set. The problem is indeed the / on the end, because the length of a base64 string should be dividable by 4 without remainder. So there should be padding on the end if necessary to achieve this. With the / on the end data is 45 characters long, which means 44 base64 characters that could be decoded to 33 bytes and then the last character which encodes only 6 bits.

Just adding padding would not solve it, because you can only add two padding characters (=) but you need one more for the missing two bits.

So you can either cut it off like this:

lenmax = len(data) - len(data)%4   
print(base64.b64decode(data[0:lenmax]).decode())

or add something like 0== to fill it up to 48 characters. But then you would get an error in decode(), and I'm not a friend of inventing extra data.

Or ask/check the code of the sender to find out, why there is this lonely / on the end.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...