Base64 编解码算法
Base64 编解码算法(模块:textEx,所在文件名 base64_hw.py,Level:★★★)
理解 Base64 编码的原理,设计两个函数实现二进制数据的编解码。
(1) Base64 编码:
函数原型:def b64en(path_in, path_out)
参数 path_in:需要进行 base64 编码的图片文件路径。
参数 path_out:以 UTF8 编码生成的文本文件路径。
返回值:无。可使用 base64 内置库。
(2) Base64 解码:
函数原型:def b64de(path_in, path_out)
参数 path_in:需要进行 base64 解码的 UTF8 文本文件路径。
参数 path_out:解码生成的图片文件路径。
返回值:无。不允许使用 base64 内置库。
代码如下(函数引用)
# -*- coding: UTF-8 -*-
import base64
def b64en(path_in, path_out):
f1 = open(path_in, 'rb')
str1 = f1.read()
f1.close()
data = base64.b64encode(str1)
data1 = str(data, encoding='UTF-8')
f2 = open(path_out, 'w+', encoding='UTF-8')
f2.write(data1)
f2.close()
def b64de(path_in, path_out):
str0 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
list0 = list(str0)
list1 = list(range(64))
list2 = []
for item in list1:
str0 = bin(item)[2:]
str0 = str0.rjust(6, '0')
list2.append(str0)
a = dict(zip(list0, list2))
# 引入文件
f0 = open(path_in, 'r+', encoding='UTF-8')
f1 = f0.read()
# 按4位处理
f1 = f1.replace('=', '')
list3 = bytearray()
while len(f1) >= 4:
char4 = f1[0:4]
f1 = f1.replace(char4, '', 1)
str1 = ''
for item in char4:
str1 += a[item]
# 取8位
s1 = str1[0:8]
s2 = str1[8:16]
s3 = str1[16:24]
c1 = int(s1, 2)
c2 = int(s2, 2)
c3 = int(s3, 2)
list3.append(c1)
list3.append(c2)
list3.append(c3)
# 处理剩余位数
str1 = ''
for item in f1:
str1 += a[item]
while len(str1) >= 8:
list3.append(int(str1[0:8], 2))
str1 = str1.replace(str1[0:8], '', 1)
# 引入输出路径
f2 = open(path_out, 'wb')
f2.write(list3)
f2.close()
if __name__ == '__main__':
b64en("./pic.jpg", "./pic_en.txt")
b64de("./pic_en.txt", "./pic_de.jpg")