base64 Incorrect Padding

MRAB python at mrabarnett.plus.com
Fri Jul 31 16:03:53 EDT 2009


Brandon Fredericks wrote:
> I did a search within this group, but couldn't find any information on
> this.
> 
> I am sending base64 encoded data as the content over http using
> urllib2 urlopen. When I receive the data and attempt to decode it, I
> get an "Incorrect Padding" error. Is there a simple way to fix this? A
> better way to send and receive the data possibly (using base64 of
> course)?

Base-64 encodes 3 bytes (echo in the range 0-255) to 4 bytes (each in a
more restricted range). The length of the output is _always_ a multiple
of 4 (ignoring whitespace); the method adds extra padding bytes (ASCII
'=') to ensure that this is the case if the length of the input isn't a
multiple of 3.

So, if decoding raises an "Incorrect Padding" error then strip out any
whitespace and append extra ASCII '=' to make its length a multiple of
3, then try decoding again. (Or you could just repeatedly add one pad
character and retry, up to 3 times.)



More information about the Python-list mailing list