Invalid base64-encoded string: number of data characters (61) cannot be 1 more than a multiple of 4

1 week ago 4
ARTICLE AD BOX

On Google colab, I'm getting the error in the subject, although I'm padding my string with three '=':

import base64 def decode_q(q: str) -> bytes: """ Decode q-value with URL-safe Base64, removing prefix '01'. """ if q.startswith("01"): q = q[2:] if padding := len(q) % 4: q += "=" * (4 - padding) try: data = base64.urlsafe_b64decode(q) except Exception as e: print(f"Problem with {q = !r}\n with {len(q) = }, {padding = }:",e) return q = '01GzAo4rlgGWP57WHO2G4KnuPaOJJ5X3tXYHJT6GS6GOyDe2bsXUaqYHbEAfust' decode_q(q)

Output :

Problem with q = 'GzAo4rlgGWP57WHO2G4KnuPaOJJ5X3tXYHJT6GS6GOyDe2bsXUaqYHbEAfust===' with len(q) = 64, padding = 1: Invalid base64-encoded string: number of data characters (61) cannot be 1 more than a multiple of 4

Strange enough, it works with a string of length 97 and 53, also padded with three '='s.

Is this a known bug? What can I do if I have 61 bytes of data?

PS: [there is a simlilar question](Invalid base64-encoded string: number of data characters (13) cannot be 1 more than a multiple of 4) for length 13, but no answer and confusing comments (somebody says "you can use 100 '='s, python truncates", s/o else says "2 '=' is the maximum".

Read Entire Article