Skip to content

Instantly share code, notes, and snippets.

@olivierlemoal
Created August 11, 2015 22:02
Show Gist options
  • Save olivierlemoal/248adf4ac4254fa13c1a to your computer and use it in GitHub Desktop.
Save olivierlemoal/248adf4ac4254fa13c1a to your computer and use it in GitHub Desktop.
Custom base64 encoder/decoder
#!/usr/bin/env python3
import base64
custom_b64 = "CDEFGHIJKLMNOPQRSTUVWXYZABcdefghijklmnopqrstuvwxyzab0123456789+/"
original_b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def encode(clear_text):
b64 = base64.b64encode(clear_text)
encoded_text = ""
for ch in b64:
ch = chr(ch)
if ch in custom_b64:
encoded_text += custom_b64[original_b64.find(ch)]
elif ch == '=':
encoded_text += "="
return encoded_text
def decode(encoded_text):
base64_eq = ""
for ch in encoded_text:
if ch in custom_b64:
base64_eq += original_b64[custom_b64.find(ch)]
elif ch == "=":
base64_eq += "="
return base64.b64decode(base64_eq.encode("ascii"))
if __name__ == "__main__":
text = b"dir\n"
encoded = encode(text)
decoded = decode(encoded)
print("Encoded : {}, Decoded : {}".format(encoded, decoded))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment