python 實現Base64編碼

python 實現Base64編碼

參考:
1、Python實現Base64編碼
2、潭州課堂亦云python加密算法之base64

"""
0. 將待轉換的字符串編碼,str->bytes
1. 將待轉換的字節流每3個分一組,共24個bits
2. 將上面的24個bits每6個分一組,共4組
3. 在每組前添加2個0構成8bits一個字節,共4個字節
4. 按上面的字節對應的10進製作爲索引,在Base64編碼表獲取對應的值
# 構建base 64 字符映射表
b64_alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'

eg:
    'hello' -> b'hello' -> b'aGVsbG8='
    'hello' - 
             - 'hel'
             - 'lo='

    1. hel -> binay
      bin(ord('h')) => '0b1101000'
        h   >   104 >   0110 1000
        e   >   101 >   0110 1000
        l   >   108 >   0110 1000
        
    2. 分組,添零,對照Base64表
        011010  >   26  >   a
        000110  >   6   >   G
        100001  >   21  >   V
        101000  >   44  >   s
"""


def base64encode(word=b'hello'):
    b64_alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    bs = []
    for i in range(0, len(word), 3):
        # print(i)
        bs.append(word[i:i+3])
    print(bs) # [b'hel', b'lo']

    # by = [j for j in i for i in bs]
    # by = [[j for j in i] for i in bs]
    # by = [[bin(j) for j in i] for i in bs]
    # by = [[bin(j).strip('0b') for j in i] for i in bs]
    # by = [['{:}'.format(bin(j).lstrip('0b')) for j in i] for i in bs]
    # by = [['{:0>8}'.format(bin(j).lstrip('0b')) for j in i] for i in bs]
    # print(by)
    # temp = [i for i in by]

    byList = []
    for subBs in bs:
        subBsList = []
        for ch in subBs:
            chBinary = bin(ch).lstrip('0b')
            chFormat = '{:0>8}'.format(chBinary)
            print(chFormat)
            subBsList.append(chFormat)
        
        byList.append(''.join(subBsList))
    print()

    all = ''
    for b in byList:
        print(b)
        for i in range(0, len(b), 6):
            newCh = b[i:i+6]
            index = len(newCh)

            if len(b) >= i + 6:
                index = int(newCh, 2)
            else:
                index = int('{:0<6}'.format(newCh), 2)
            currChar = b64_alphabet[index]
            
            print(newCh, index, currChar)
            print()

            all += currChar

    if len(word) % 3 == 1:
        all += '=='
    elif len(word) % 3 == 2:
        all += '='

    print(all)

    return all.encode('utf-8')


if __name__ == "__main__":
    enString = base64encode()
    print(enString)

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章