Skip to content

Instantly share code, notes, and snippets.

@bilzard
Last active August 19, 2022 17:25
Show Gist options
  • Save bilzard/d9c780a6f1ad6979f0f14dd8bd8817ee to your computer and use it in GitHub Desktop.
Save bilzard/d9c780a6f1ad6979f0f14dd8bd8817ee to your computer and use it in GitHub Desktop.
class Base64:
import string
import binascii
def __init__(self):
b64chars = (
string.ascii_uppercase + string.ascii_lowercase + string.digits + "+/"
)
self.c2i = {c: i for i, c in enumerate(b64chars)}
self.c2i["="] = 0
self.i2c = {i: c for i, c in enumerate(b64chars)}
def decode(self, b64str):
bit_str = "".join([f"{self.c2i[c]:06b}" for c in b64str])
decoded = [chr(int(b, 2)) for b in into_chunk(bit_str, 8)]
decoded = "".join([c for c in decoded if c != "\x00"])
return decoded
def encode(self, ascii_str):
bit_str = "".join([f"{ord(b):08b}" for b in ascii_str])
pad = -len(bit_str) % 6
bit_str += "0" * pad
encoded = [self.i2c[int(b, 2)] for b in into_chunk(bit_str, 6)]
encoded = "".join(encoded)
pad = -len(encoded) % 4
encoded += "=" * pad
return encoded
@classmethod
def into_chunk(bit_str, chunk_size):
return [bit_str[i : i + chunk_size] for i in range(0, len(bit_str), chunk_size)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment