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)

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值