Encode base64 in JavaScript and Decode in Python: Part 2
Learn how to decode a Base64 string you encoded from JavaScript in Python
Published: 15 Oct, 2023
In Part 1 of this series, I encoded a string in URL-safe base64 format from my front-end application.
Recall that I encoded /Users/data/mystuff
and received L1VzZXJzL2RhdGEvbXlzdHVmZg==
back. Regular base64 returns L1VzZXJzL2RhdGEvbXlzdHVmZg==
instead, which includes the URL-unsafe =
character.
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. According to the Python decoder, the =
is URL-safe for some reason.
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’s unsafe to be embedded in URLs.