【发布时间】:2020-12-13 12:46:21
【问题描述】:
我正在使用 AES 加密和解密图像。我已经继承了代码,所以如果你们发现有问题,请指导我。我正在尝试理解并修复代码。
chunk_size = 64*1024
output_file = filename+".enc"
file_size = bytes(os.path.getsize(filename))
IV = get_random_bytes(16)
encryptor = AES.new(key, AES.MODE_CBC, IV)
with open(filename, 'rb') as inputfile:
with open(output_file, 'wb') as outf:
outf.write(file_size)
outf.write(IV)
while True:
chunk = bytes(inputfile.read(chunk_size))
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk = chunk + bytes(16 - len(chunk)%16)
outf.write(encryptor.encrypt(chunk))
我的图片大小为 66 kb,大约为 67584 字节。考虑到 AES 使用 16 个字节,此代码应该会出错,但它会生成加密文件。当我尝试使用解密时
def decrypt(key, filename):
chunk_size = 64*1024
output_file = filename[:-4]
with open(filename, 'rb') as inf:
filesize = bytes(inf.read(16))
IV = inf.read(16)
decryptor = AES.new(key, AES.MODE_CBC, IV)
with open(output_file, 'wb') as outf:
while True:
chunk = inf.read(chunk_size)
print(len(chunk))
if len(chunk)==0:
break
outf.write(decryptor.decrypt(chunk))
outf.truncate(filesize)```
我收到如下错误
TypeError:需要一个整数(获取类型字节)
当我以字节为单位输入块时,我收到以下错误
输入字符串的长度必须是 16 的倍数
当我在控制台上的源文件大小显示为 65536 时,我很困惑如何修复错误“长度为 16 的倍数”。
【问题讨论】:
-
AES primitive 一次只处理 128 位数据,但 CBC mode 处理任意大的数据;见en.wikipedia.org/wiki/Block_cipher_mode_of_operation
标签: python-3.x encryption