I want to implement AES_CBC mode encryption, using ECB encoder from Crypto package. But my code run quite slow (about 1s for 1MB data, while it is just 0.02s when encrypt with AES_CBC mode from Crypto package). Below is my code, any recommend for speed up?
from Crypto.Cipher import AES
from Crypto.Util import Padding
from Crypto.Random import get_random_bytes
from Crypto.Util import strxor as XOR
import time
import os
from base64 import b64encode
block_size = 16
key = b'12345678abcdedgh'
#encrypt and decrypt a block data with AES_ECB from Crypto package
def encrypt_ecb(ecb,xored_block):
return ecb.encrypt(xored_block)
def decrypt_ecb(ecb,block):
return ecb.decrypt(block)
#name is filename to encrypt, en_name is file name where I write result to
def encrypt_cbc(name, en_name):
#read data
file = open(name,'rb')
data_byte = file.read()
#Padding
data_byte = Padding.pad(data_byte,block_size)
output_file = open(en_name, 'wb')
ecb = AES.new(key,AES.MODE_ECB)
IV = get_random_bytes(16)
print('My IV is: ' + str(IV))
output_file.write(IV)
state = IV
output_data = []
start = time.time()
for i in range(0,len(data_byte),block_size):
block = data_byte[i:i+16]
y = encrypt_ecb(ecb,XOR.strxor(state,block,None))
# output_data.append(y)
output_file.write(y)
state = y
end = time.time()
print('Time to encrypt data: ' + str(end - start))
print('Done')