binascii.Error: Invaild base64-encoded string: number of data characters(1957) cannot be 1 more than a multiple of 4

Viewed 16591

I was trying to decode a string to base64, then decompress it to zlib, but this message came out:

binascii.Error: Invaild base64-encoded string: number of data characters(1957) cannot be 1 more than a multiple of 4

Code:

def decode_token(token):
    # token is a string
    token_decode = base64.b64decode(token.encode())
    token_string = zlib.decompress(token_decode)
    return token_string
4 Answers
  1. Try padding your input with the correct number (1,2 or 3) of = characters so as to make its final length a multiple of 4. Skip that step if your token length is already a multiple of 4 (len(padded_token)%4 == 0).

  2. You might get the same error still if your input is using characters -_ in which case it means it is urlsafe encoded. In that case use base64.urlsafe_b64decode rather than base64.b64decode to decode it.

The error basically means that your base64 input is incorrect. The base64 encoding converts every 3 input bytes to 4 ASCII characters from a restricted set, but the data you passed in seems to decode to something which is not an even multiple of 3 bytes -- it's as if a 2/3 byte slipped in, and there is no way to decode that. Quite simply, your input is corrupted. (You can try to drop one character from the base64 and see if you manage to decode correctly, but then how do you know if the decoded data is correct, or just gibberish?)

I've also got this error because of modifying a session cookie. When I accessed the django server(localhost:8000) via chrome, i got this error but then using incognito mode, it worked.

The solution was to clear my cookies. I hope that helps somebody!

I was sending a base64 audio file using json.

On the server received this data:

data:audio/webm;codecs=opus;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKH
gQRChYECGFOAZwH/////////FUmpZpkq17GDD0JATYCGQ2hyb21lV0GGQ2hyb21lFlSua7+uvde
BAXPFh92N22LbK2CDgQKGhkFfT1BVU2Oik09wdXNIZWFkAQEAAIC7AAAAAADhjbWERzuAAJ+BAW
JkgSAfQ7Z1Af/////////ngQCjQYaBAACA+4OtX338PBu4bnSDfneNZGIiUHyTxHm2rT3E/1TL9
cIOCOstqZXLLpCP+SCP02KLi/+szgCGgHJQONOc4x9WBImn0XDNhgIcAG4wpEAVLEr53fnM8Pcw
ouC5etV7QAcFxIJtdQbRLYZmSmFsMi41YIAoBe7+JTHVSfMOSsE2cEqejD4nkBeDj4kX9but6xE
LHo+6gG2HkYWmlG/c0nNb31DuhT+SA8Go+MRhlB7wfmg/p4kNjbpxFYJX3yOphnkBTxQyADZd8
71n1ddOWeNmBX8Ss9zShKP2pF3I8CCakBTQp4nXaDqO8oY0PVJJcs1sAwiEVgUG813MNCeP8K5
8IR9B980S8KfXO1AqZINNPy6YQA6M=

The base64 itself starts after:

data:audio/webm;codecs=opus;base64,

You may also have additional data.

Related