我想使用简单的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')))
as
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中,如果您传递字符串,它会引发异常。 - t.m.adam