I am using Pycrypto encrypter and decrypter with AES 256 Symmetric key algorithm. My encryption part is taking much more time in comparison to decryption time. Is there any good reason for it?
I tried on 16 MB file:
Encryption time = 3.31 secs
Decryption time = 0.18 secs
Can someone help me in telling what could be the reason for this?
Encryption Logic Looks like below:
def encrypt_file(key, infile, chunksize=64 * 1024):
""" Encrypts a file using AES (CBC mode) with the
given key.
key:
The encryption key - a string that must be
either 16, 24 or 32 bytes long. Longer keys
are more secure.
infile:
input file
chunksize:
Sets the size of the chunk which the function
uses to read and encrypt the file. Larger chunk
sizes can be faster for some files and machines.
chunksize must be divisible by 16.
"""
iv = os.urandom(16)
encryptor = AES.new(key, AES.MODE_CBC, iv)
infile.seek(0, os.SEEK_END)
filesize = infile.tell()
infile.seek(0, os.SEEK_SET)
encrypted = b'';
encrypted += struct.pack('<Q', filesize)
encrypted += iv
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += b' ' * (16 - len(chunk) % 16)
encrypted += encryptor.encrypt(chunk)
return encrypted
And Decryption logic looks like below:
def decrypt_file(key, infile, out_filename, chunksize=24*1024):
""" Decrypts a file using AES (CBC mode) with the
given key.
"""
if key == '':
with open(out_filename, 'wb') as outfile:
for line in infile:
outfile.write(line)
return outfile.name
origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
iv = infile.read(16)
decryptor = AES.new(key, AES.MODE_CBC, iv)
# for line in infile:
# print(line)
with open(out_filename, 'wb+') as outfile:
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
outfile.write(decryptor.decrypt(chunk))
outfile.truncate(origsize)
return outfile.name