Created
December 26, 2022 00:04
-
-
Save Wind010/0e476caabddae14c56208fd6b492f8a1 to your computer and use it in GitHub Desktop.
Used for better understanding of Base64 encoding.
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
def solution(encoding, message): | |
class BaseEncoder(): | |
BASE64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' | |
UTF_8_BYTE_SIZE, B64_BYTE_SIZE, BINARY_BASE = 8, 6, 2 | |
@staticmethod | |
def encode(message, in_byte_size, out_byte_size, char_set): | |
enc_msg, padding = '', '' | |
# Get the ascii code and convert that to binary. ord('A') = 65; bin(65) = 0b1000001 | |
# Pad right with zero since ASCII is 7-bit and we want 8-bit bytes before chunking to 6-bit bytes. | |
message_in_binary = "".join( | |
format(ord(x), 'b').zfill(in_byte_size) for x in message) | |
for i in range(0, len(message_in_binary), out_byte_size): | |
chunk = message_in_binary[i:i + out_byte_size] | |
if len(chunk) < out_byte_size: | |
diff = out_byte_size - len(chunk) | |
chunk += '0' * diff # or chunk.zfill(out_byte_size) | |
padding = '=' * (diff // 2) | |
enc_msg += char_set[int(chunk, BaseEncoder.BINARY_BASE)] | |
return enc_msg + padding | |
@staticmethod | |
def decode(message, in_byte_size, out_byte_size, char_set): | |
# Get dictionary of character to index of the base64 table. | |
message = message.replace('=', '') | |
dec_msg = '' | |
d_char_to_index = {c: i for i, c in enumerate(char_set)} | |
# Get binary representation of the b64 character codes and ensure padded 6-bit chunks. | |
message_in_binary = ''.join([ | |
format(d_char_to_index[c], 'b').zfill(in_byte_size) | |
for c in message | |
]) | |
for i in range(0, len(message_in_binary), out_byte_size): | |
chunk = message_in_binary[i:i + out_byte_size].zfill(out_byte_size) | |
if chunk != '0' * out_byte_size: | |
# Handle the last padded string. Probably at end of string anyways. | |
dec_msg += chr(int(chunk, BaseEncoder.BINARY_BASE)) | |
return dec_msg | |
alt_base64_chars = BaseEncoder.BASE64_CHARS[:-2] + encoding | |
return BaseEncoder.decode(message, BaseEncoder.B64_BYTE_SIZE, BaseEncoder.UTF_8_BYTE_SIZE, | |
alt_base64_chars) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment