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)