[Django]-Django urlsafe base64 decoding with decryption

41👍

The problem is that b64decode quite explicitly can only take bytes (a string), not unicode.

>>> import base64
>>> test = "Hi, I'm a string"
>>> enc = base64.urlsafe_b64encode(test)
>>> enc
'SGksIEknbSBhIHN0cmluZw=='
>>> uenc = unicode(enc)
>>> base64.urlsafe_b64decode(enc)
"Hi, I'm a string"
>>> base64.urlsafe_b64decode(uenc)
Traceback (most recent call last):
...
TypeError: character mapping must return integer, None or unicode

Since you know that your data only contains ASCII data (that’s what base64encode will return), it should be safe to encode your unicode code points as ASCII or UTF-8 bytes, those bytes will be equivalent to the ASCII you expected.

>>> base64.urlsafe_b64decode(uenc.encode("ascii"))
"Hi, I'm a string"

3👍

I solved the problem!

deserialized = pickle.loads(captcha_decrypt(urlsafe_b64decode(key.encode('ascii'))))
return HttpResponse(str(deserialized))

But still I don’t understand, why it didn’t work first time.

Leave a comment