Last active
July 16, 2024 20:44
-
-
Save cameronmaske/f520903ade824e4c30ab to your computer and use it in GitHub Desktop.
base64 that actually encodes URL safe (no '=' nonsense)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here are 2 one-liners for encoding and decoding:
Examples:
Encoding:
Decoding
Note
It does require
base64
'surlsafe_b64encode
andurlsafe_b64decode
to be imported like thisThis can be easily changed, as all you need to do is change the calls to the functions (right after
(lambda string:
)