Python解码base64遇到Incorrect padding错误

时间:2023-03-08 23:55:51
Python解码base64遇到Incorrect padding错误

Python解码base64遇到Incorrect padding错误

base64转码过程

先说一下转换过程,详细的可以参考阮一峰廖雪峰博客

所谓Base64,就是说选出64个字符----小写字母a-z、大写字母A-Z、数字0-9、符号"+"、"/"(再加上作为垫字的"=",实际上是65个字符)----作为一个基本字符集。然后,其他所有符号都转换成这个字符集中的字符。

具体来说,转换方式可以分为四步。

第一步,将每三个字节作为一组,一共是24个二进制位。

第二步,将这24个二进制位分为四组,每个组有6个二进制位。

第三步,在每组前面加两个00,扩展成32个二进制位,即四个字节。

第四步,根据下表,得到扩展后的每个字节的对应符号,这就是Base64的编码值。

  0 A  17 R   34 i   51 z

  1 B  18 S   35 j   52 0

  2 C  19 T   36 k   53 1

  3 D  20 U   37 l   54 2

  4 E  21 V   38 m   55 3

  5 F  22 W   39 n   56 4

  6 G  23 X   40 o   57 5

  7 H  24 Y   41 p   58 6

  8 I   25 Z   42 q   59 7

  9 J  26 a   43 r   60 8

  10 K  27 b   44 s   61 9

  11 L  28 c   45 t   62 +

  12 M  29 d   46 u   63 /

  13 N  30 e   47 v

  14 O  31 f   48 w   

  15 P  32 g   49 x

  16 Q  33 h   50 y

因为,Base64将三个字节转化成四个字节,因此Base64编码后的文本,会比原文本大出三分之一左右。

http://www.ruanyifeng.com/blog/2008/06/base64.html

如果要编码的二进制数据不是3的倍数,最后会剩下1个或2个字节怎么办?Base64用\x00字节在末尾补足后,再在编码的末尾加上1个或2个=号,表示补了多少字节,解码的时候,会自动去掉。

https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431954588961d6b6f51000ca4279a3415ce14ed9d709000

Incorrect 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)

我试了试,其实还是同样的错误,看来并不是等号的问题。

继续尝试,又有人说可能是末尾多了字符,可尝试去掉,方法如下:

lens = len(strg)
lenx = lens - (lens % 4 if lens % 4 else 4)
try:
result = base64.decodestring(strg[:lenx])
except etc

我又试了试,还是不行~看来也不是这个问题

再往下看,看到了这个

Update 2: It is possible that the encoding has been done in an url-safe manner. If this is the case, you will be able to see minus and underscore characters in your data, and you should be able to decode it by using base64.b64decode(strg, '-_')

意思是如果你解码的是url(咦,我就是处理url),可以这么尝试

base64.b64decode(strg, '-_')

试了一下,然也。

那么为什么会出现这种情况呢?继续查看原因,终于找到了:

由于标准的Base64编码后可能出现字符+/,在URL中就不能直接作为参数,所以又有一种"url safe"的base64编码,其实就是把字符+/分别变成-_

https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431954588961d6b6f51000ca4279a3415ce14ed9d709000

然后,我们这个问题又有另外一个解决方式了:

base64.urlsafe_b64decode(base64_url)