天天看點

python的base64編碼代碼實作

python的base64編碼代碼實作(學習記錄)

base64_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
               'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
               'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
               'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/']


def encode_ascii(string: str) -> str:
    temp = ''
    base = ''

    # 把原始字元串轉換為二進制,用bin轉換後去掉開頭的0b,首位補0補齊8位
    for i in string:
        temp += '{:08}'.format(int(str(bin(ord(i))).replace('0b', '')))

    # 6位一組截取,最後一組不足6位的後面補0,擷取base_list中對應的字元
    for j in range(0, len(temp), 6):
        t = '{:<06}'.format(temp[j: j + 6])
        base += base64_list[int(t, 2)]

    # 判斷base字元長度結尾補‘=’
    if len(string) % 3 == 1:
        base += '=='
    elif len(string) % 3 == 2:
        base += '='
    return base


def decode_ascii(base: str) -> str:
    temp = ''
    string = ''

    # 去掉尾補的‘=’
    base = base.replace('=', '')
    # 擷取base在base_list中的索引,轉換為二進制,用bin轉換後去掉開頭的0b,首位補0補齊6位
    for s in range(len(base)):
        temp += '{:06}'.format(int(str(bin(base64_list.index(base[s]))).replace('0b', '')))

    # 8位一組截取(已忽略最後一組),轉10進制,擷取ASCII字元
    for i in range(len(temp) // 8):
        string += chr(int(temp[8 * i: 8 * i + 8], 2))

    return string


# 使用utf8支援中文
def encode(string: str, encoding: str = 'utf8') -> str:
    temp = ''
    base = ''

    # 擷取字元串編碼
    string = string.encode(encoding)

    # 把字元串編碼為二進制,用bin轉換後去掉開頭的0b,首位補0補齊8位
    for i in string:
        temp += '{:08}'.format(int(str(bin(i)).replace('0b', '')))

    # 6位一組截取,最後一組不足6位的後面補0,擷取base_list中對應的字元
    for j in range(0, len(temp), 6):
        t = '{:<06}'.format(temp[j: j + 6])
        base += base64_list[int(t, 2)]

    # 判斷base字元長度結尾補‘=’
    if len(string) % 3 == 1:
        base += '=='
    elif len(string) % 3 == 2:
        base += '='
    return base


def decode(base: str, encoding: str = 'utf8') -> str:
    temp = ''
    string_bytes = []

    # 去掉尾補的‘=’
    base = base.replace('=', '')
    # 擷取base在base_list中的索引,轉換為二進制,用bin轉換後去掉開頭的0b,首位補0補齊6位
    for s in range(len(base)):
        temp += '{:06}'.format(int(str(bin(base64_list.index(base[s]))).replace('0b', '')))

    # 8位一組截取(已忽略最後一組),轉10進制
    for i in range(len(temp) // 8):
        string_bytes.append(int(temp[8 * i: 8 * i + 8], 2))

    # 根據編碼擷取源字元串
    return bytes(string_bytes).decode(encoding)


# Demo
v = '人人a'
print(v)

v = encode(v)
print(v)

v = decode(v)
print(v)