【发布时间】:2018-11-29 03:14:09
【问题描述】:
我想用简单的AES加密来加密文件,这是我的python3源代码。
import os, random, struct
from Crypto.Cipher import AES
def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):
if not out_filename:
out_filename = in_filename + '.enc'
iv = os.urandom(16)
encryptor = AES.new(key, AES.MODE_CBC, iv)
filesize = os.path.getsize(in_filename)
with open(in_filename, 'rb') as infile:
with open(out_filename, 'wb') as outfile:
outfile.write(struct.pack('<Q', filesize))
outfile.write(iv)
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += ' ' * (16 - len(chunk) % 16)
outfile.write(encryptor.encrypt(chunk.decode('UTF-8','strict')))
它对某些文件工作正常,遇到一些文件的错误信息,如下所示:
encrypt_file("qwertyqwertyqwer",'/tmp/test1' , out_filename=None, chunksize=64*1024)
没有错误信息,工作正常。
encrypt_file("qwertyqwertyqwer",'/tmp/test2' , out_filename=None, chunksize=64*1024)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 17, in encrypt_file
UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 65534-65535: unexpected end of data
如何修复我的 encrypt_file 函数?
按照t.m.adam 说的做,修复
outfile.write(encryptor.encrypt(chunk.decode('UTF-8','strict')))
作为
outfile.write(encryptor.encrypt(chunk))
尝试一些文件。
encrypt_file("qwertyqwertyqwer",'/tmp/test' , out_filename=None, chunksize=64*1024)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 16, in encrypt_file
TypeError: can't concat bytes to str
【问题讨论】:
-
你为什么要解码你的数据?
.encrypt()可以处理字节,实际上在Python3中,如果你传递一个字符串,它会引发异常。 -
TypeError: can't concat bytes to str
-
你能给我整个 python encrypt_file 函数吗?
标签: python python-3.x encryption