ValueError: Data must be aligned to block boundary in ECB mode

Jozf picture Jozf · Sep 5, 2018 · Viewed 8.2k times · Source

I am trying aes 128 encryption in ECB mode with the following code.

from Crypto.Cipher import AES
key = 'abcdefghijklmnop'
cipher = AES.new(key.encode('utf8'), AES.MODE_ECB)
msg = cipher.encrypt(b'hello')
print(msg.hex())
decipher = AES.new(key.encode('utf8'), AES.MODE_ECB)
msg_dec = decipher.decrypt(msg)
print(msg_dec)

but I'm getting "ValueError: Data must be aligned to block boundary in ECB mode". It works fine if string is a multiple of 16. I don't know how to do padding, unpadding. How can we solve this ? Please help

Answer

AB Abhi picture AB Abhi · Jun 14, 2019

For padding and un-padding, you may use inbuilt functions of Crypto library, below is a working solution to your problem.

from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import AES
BLOCK_SIZE = 32 # Bytes

key = 'abcdefghijklmnop'
cipher = AES.new(key.encode('utf8'), AES.MODE_ECB)
msg = cipher.encrypt(pad(b'hello', BLOCK_SIZE))
print(msg.hex())
decipher = AES.new(key.encode('utf8'), AES.MODE_ECB)
msg_dec = decipher.decrypt(msg)
print(unpad(msg_dec, BLOCK_SIZE))