Encode base64 in JavaScript and Decode in Python: Part 2

Learn how to decode the string you previously encoded from JavaScript

In Part 1 of this series, you’ll take the string you previously encoded and decode it in Python.

Recall that you encoded /Users/data/mystuff and received L1VzZXJzL2RhdGEvbXlzdHVmZg== back.

Then, you stripped the == characters at the end so that you could pass it around in URLs. You’re now left with L1VzZXJzL2RhdGEvbXlzdHVmZg.

Can you decode this directly in Python? Try it now:

from base64 import urlsafe_b64decode

urlsafe_b64decode('L1VzZXJzL2RhdGEvbXlzdHVmZg'.encode('utf-8-))
>>> binascii.Error: Incorrect padding

Oops, Incorrect padding.

In Base64, the = sign is used for padding. The encoder will check if the resulting string is divisible by 4, if it’s not, it will add enough = signs for this to happen.

All we have to do is reconstruct the original padding:

s = 'L1VzZXJzL2RhdGEvbXlzdHVmZg'

pads_missing = len(s) % 4

if pads_missing > 0:
  s = s + (4 - pads_missing)
  
urlsafe_b64decode(s.encode(‘utf-8’))

You'll now end up with the origin L1VzZXJzL2RhdGEvbXlzdHVmZg== string.

Awesome, now you know how to send weird looking data that unsafe to be embedded in URLs.