Created
December 1, 2021 19:38
-
-
Save MFDGaming/e3abce7ba8a20370e80f3beb591ab34a to your computer and use it in GitHub Desktop.
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
# Copyright MFDGaming 2021 | |
base64_table = r"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" | |
def b64encode(value: bytes) -> str: | |
result = "" | |
padding = 0 | |
for i in range(2): | |
if len(value) * 8 % 6 != 0: | |
padding += 1 | |
value += b"\x00" | |
else: | |
break | |
for i in range(0, len(value), 3): | |
prt24 = value[i] << 16 | value[i + 1] << 8 | value[i + 2] | |
for ii in range(0, 4 - (padding if i == len(value) - padding - 2 else 0)): | |
index = (prt24 >> (18 - (6 * ii))) & 63 | |
result += base64_table[index] | |
return result + "=" * padding | |
def b64decode(value: str) -> bytes: | |
result = b"" | |
tb = [] | |
padding = 0 | |
for entry in value: | |
if entry == "=": | |
padding += 1 | |
else: | |
tb.append(base64_table.index(entry)) | |
for i in range(0, 3): | |
if len(tb) % 4: | |
tb.append(0) | |
else: | |
break | |
for i in range(0, len(tb), 4): | |
prt24 = (((tb[i] << 6) | tb[i + 1]) << 12) | ((tb[i + 2] << 6) | tb[i + 3]) | |
result += bytes([(prt24 >> 16) & 0xff]) | |
result += bytes([(prt24 >> 8) & 0xff]) | |
result += bytes([prt24 & 0xff]) | |
return result[:-padding] | |
print(b64encode(b"Hello world")) | |
print(b64decode("CgAACQQAZW5jaAoBAAAAAgIAaWQAAAIDAGx2bAEAAAA=")) | |
print(b64decode(b64encode(b"Hello world"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment