代码之家  ›  专栏  ›  技术社区  ›  Saqib Ali

如何在Python中Base64解码此字符串时避免“不正确的填充”错误

  •  1
  • Saqib Ali  · 技术社区  · 6 年前

    我有以下字符串,我想使用Python对其进行Base64解码。

    2.2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2JHKOTC1NTLLNJJJZPKAwqioi2 JHZTQWOWYWYTbjiIwic3 ViijoinotKymyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWyWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWiWuL5prluY70sU-0W5XvWIB-XMTRLZ7LJWHEGWTSKWF81\U HBq\U MSB75RMFTEBWBMOJ4ITMHDNXKSZ8W7EDOWUPSEFFT5XLMND16ZTEOY5DDU IQNEBT567FCAJAEXV0FW6H\U OUT GLYPDANKCJ6CWJ7DPA0JBQERR9DESZALWYNZBDPWD0YEAIMEEDZMB0AMTL4R87KK6KKK6KKKK7KKKKL7KKL7KKKKL7KKKL7KKKKKKLKKKKKKKLKKL7LKKKK8W

    当我去这个 https://www.base64decode.org/ 我可以看到解码字符串的第一部分是可读的纯文本:

    enter image description here

    但是,当我尝试使用Python对其进行解码时,它失败了:

    >>> import base64
    >>> x = "eyJ......"
    >>> base64.b64decode(x)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/base64.py", line 76, in b64decode
        raise TypeError(msg)
    TypeError: Incorrect padding
    

    我试过了 this remedy

    1 回复  |  直到 6 年前
        1
  •  9
  •   djvg mozman2    4 年前

    嗯,看起来这条消息是由 .

    import base64
    
    res = "eyJqa3UiOiJodHRwczovL2U5N2I4YTlkNjcyZTRjZTQ4NDVlYzY5NDdjZDY2ZWY2LXNiLmJhYXMubmludGVuZG8uY29tLzEuMC4wL2NlcnRpZmljYXRlcyIsImtpZCI6ImZlOWRiYmZmLTQ3MGItNDZjOC04YmFmLTFiNzY5OGRlZTViZSIsImFsZyI6IlJTMjU2In0.eyJpc3MiOiJodHRwczovL2U5N2I4YTlkNjcyZTRjZTQ4NDVlYzY5NDdjZDY2ZWY2LXNiLmJhYXMubmludGVuZG8uY29tIiwiZXhwIjoxNTQ1MTg1NDk2LCJ0eXAiOiJpZF90b2tlbiIsImF1ZCI6IjhkOTc1NTllNjNlY2NkNTYiLCJiczpkaWQiOiI2NjJhZTQwOWYwNTQyYTBjIiwic3ViIjoiOTNkYmYwNDdiYTI3NzQ5NSIsImp0aSI6IjY1NDg4ZjJmLTI1NzAtNDBkYy04ODQ3LTMzODNlZWIxMGJiYiIsIm5pbnRlbmRvIjp7ImFpIjoiMDEwMGY4MDAwMDQ5MjAwMCIsImF2IjoiMDAwMCIsImVkaSI6ImJjNTdiYmM3MTZlMDA1MGFmOWRhN2NkYTIzMWRjZDgyIiwiYXQiOjE1NDUxNzQ2OTZ9LCJpYXQiOjE1NDUxNzQ2OTZ9.ZMUIt3wYrbfhXnnDh4WraGlKrZy0YuL5prluY70sU_-0W5XvWIB-xmTrLz7LJWHEGwTskcWf81_HBq_mSb75rMfTAEBwBmOJ4ITmhdnXksz8w7EDOWuPPSEft5XLMNOMD16ztEOYe5ddU_iqNEbT56L7fcAJEXv0FWy6H_OutxOglYpDaNkcj6CWJ7dpA0JbqerR9dEszaLwyn1ZBDPVD0YeAIm5bEr61imeedzMb0amxlTl4R87mqK6epsFUnRy6p6Klr27_DlTLQ-gej09W7NeNzONCj4thHgCr9szAiaN28krfTc2fobz3qFCoC_eQghiIIZBe_-Lksng3Eg6tw"
    
    for i in res.split("."):
        print(base64.b64decode(i + '=' * (-len(i) % 4)))
    

    我猜最后一个是签名,用于验证前两部分。你是从饼干里得到这个字符串的吗?还是从提交的表格?

    编辑

    因此,对于任何看到这个答案的人来说,给定的字符串是一个 JWT 一串