Skip to content

Instantly share code, notes, and snippets.

@cameronmaske
Last active February 5, 2024 19:16
Show Gist options
  • Save cameronmaske/f520903ade824e4c30ab to your computer and use it in GitHub Desktop.
Save cameronmaske/f520903ade824e4c30ab to your computer and use it in GitHub Desktop.
base64 that actually encodes URL safe (no '=' nonsense)
"""
base64's `urlsafe_b64encode` uses '=' as padding.
These are not URL safe when used in URL paramaters.
Functions below work around this to strip/add back in padding.
See:
https://docs.python.org/2/library/base64.html
https://mail.python.org/pipermail/python-bugs-list/2007-February/037195.html
"""
import base64
def base64_encode(string):
"""
Removes any `=` used as padding from the encoded string.
"""
encoded = base64.urlsafe_b64encode(string)
return encoded.rstrip("=")
def base64_decode(string):
"""
Adds back in the required padding before decoding.
"""
padding = 4 - (len(string) % 4)
string = string + ("=" * padding)
return base64.urlsafe_b64decode(string)
>>> test = "helloworld"
>>> encode_base64(test)
'aGVsbG93b3JsZA'
>>> e = encode_base64(test)
>>> decode_base64(e)
'helloworld'
>>> test = "Hello World"
>>> encoded = encode_base64(test)
>>> print encoded
SGVsbG8gV29ybGQ
>>> decoded = decode_base64(encoded)
>>> decoded
'Hello World'
>>> decoded == test
True
@AveragePythonEnjoyer29
Copy link

AveragePythonEnjoyer29 commented Mar 22, 2023

Here are 2 one-liners for encoding and decoding:

(lambda string: urlsafe_b64encode(string).strip(b"="))(b"this will be converted into base64!")
(lambda string: urlsafe_b64decode((string+(b"="*(4-(len(string)%4))))))(b"this will be converted back into base64!")

Examples:

Encoding:

>>> (lambda string: urlsafe_b64encode(string).strip(b"="))(b"this will be converted into base64!")
b'dGhpcyB3aWxsIGJlIGNvbnZlcnRlZCBpbnRvIGJhc2U2NCE'

Decoding

>>> (lambda string: urlsafe_b64decode((string+(b"="*(4-(len(string)%4))))))(b'dGhpcyB3aWxsIGJlIGNvbnZlcnRlZCBpbnRvIGJhc2U2NCE')
b'this will be converted into base64!'

Note

It does require base64's urlsafe_b64encode and urlsafe_b64decode to be imported like this

from base64 import urlsafe_b64encode, urlsafe_b64decode

This can be easily changed, as all you need to do is change the calls to the functions (right after (lambda string:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment