Search code examples
pythonbase32

Ignore a padding exception when base32 decoding using b32decode from base64 lib


I need a way to ignore the 'incorrect padding' exception when trying to decode a base32 string using base64 lib.

I have seen this post Python: Ignore 'Incorrect padding' error when base64 decoding which resolves the problem for base64 (b64decode) decoding. I tried to do the same (add the maximum number of accepted paddings, which if I'm not msitaken is 6 for base32) like this

b32decode(str(decoding) + "======", True, None)

But the exception raises anyway.

The expected result is to have a base32 string decoded anyway even without the correct padding:

decoding = JBSWY3DPEBZXIYLDNMQG65TFOJTGY33XEE== #this string should have 6 '=' as padding
print(b32decode(str(decoding) + "======", True, None))
>> Hello stack overflow! 

Solution

  • Background

    A base32 character contains 5 bits of data. The input to the encoder comes in the form of bytes (8 bits). This creates some awkwardness. Like when encoding one byte, you get 5+3 bits, with two bytes, you get 5+5+5+1 bits, and so on.

    The only time things are not awkward is when there's 40 bits, because it will perfectly fit 5 bytes (ASCII characters) of input, and 8 base32-characters of output.

    And so, the RFC4648 standard states that when things do not align, padding characters (=) are added until it does.

    So, if an unpadded string is evenly divisible by 8, no action needs to be taken. Otherwise, padding characters must be added so that it aligns with the 40-bit a.k.a. 8 base32-character blocks.

    Solution

    last_block_width = len(unpadded_str) % 8
    if last_block_width != 0:
      unpadded_str += (8 - last_block_width) * '='