Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

aes

ecb

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

like image 932
Jozf Avatar asked Sep 05 '18 09:09

Jozf


1 Answers

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))
like image 184
AB Abhi Avatar answered Oct 27 '22 00:10

AB Abhi