Python: Ignore 'Incorrect padding' error when base64 decoding
base64, python
Solution
It seems you just need to add padding to your bytes before decoding. There are many other answers on this question, but I want to point out that (at least in Python 3.x) `base64.b64decode` will truncate any extra padding, provided there is enough in the first place.
So, something like: `b'abc='` works just as well as `b'abc=='` (as does `b'abc====='`).
What this means is that you can just add the maximum number of padding characters that you would ever need—which is two (`b'=='`)—and base64 will truncate any unnecessary ones.
This lets you write:
base64.b64decode(s + b'==')
which is simpler than:
base64.b64decode(s + b'=' * (-len(s) % 4))
Note that if the string `s` already has some padding (e.g. `b"aGVsbG8="`), this approach will only work if the `validate` keyword argument is set to `False` (which is the default). If `validate` is `True` this will result in a `binascii.Error` being raised if the total padding is longer than two characters.
From the docs:
If validate is `False` (the default), characters that are neither in the normal base-64 alphabet nor the alternative alphabet are discarded prior to the padding check. If validate is `True`, these non-alphabet characters in the input result in a `binascii.Error`.
However, if `validate` is `False` (or left blank to be the default) you can blindly add two padding characters without any problem. Thanks to eel ghEEz for pointing this out in the comments.
Problem
I have some data that is base64 encoded that I want to convert back to binary even if there is a padding error in it. If I use ``` base64.decodestring(b64_string) ``` it raises an 'Incorrect padding' error. Is there another way? UPDATE: Thanks for all the feedback. To be honest, all the methods mentioned sounded a bit hit and miss so I decided to try openssl. The following command worked a treat: ``` openssl enc -d -base64 -in b64string -out binary_data ```