-
-
Save bjinwright/3e1c71988e788fe10cb44889195ab42a to your computer and use it in GitHub Desktop.
base64 that actually encodes URL safe (no '=' nonsense)
This file contains 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 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