Last active
August 19, 2022 17:25
-
-
Save bilzard/d9c780a6f1ad6979f0f14dd8bd8817ee to your computer and use it in GitHub Desktop.
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
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