I want to encrypt file with simple AES encryption,here is my python3 source code.
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')))
It works fine for some files,encounter error info for some files such as below:
encrypt_file("qwertyqwertyqwer",'/tmp/test1' , out_filename=None, chunksize=64*1024)
No error info,works fine.
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
How to fix my encrypt_file function?
Do as t.m.adam
say ,to fix
outfile.write(encryptor.encrypt(chunk.decode('UTF-8','strict')))
as
outfile.write(encryptor.encrypt(chunk))
To try with some file.
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
from UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 65534-65535: unexpected end of data
No comments:
Post a Comment