Jozf
Jozf

Reputation: 161

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

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

Upvotes: 9

Views: 24042

Answers (2)

Walulya francis
Walulya francis

Reputation: 573

improving on @Abhishake Gupta's answer using pycryptodomex pip install pycryptodomex

import base64
from Cryptodome.Cipher import AES
from Cryptodome.Util.Padding import pad, unpad
###################
class Cryptor:
    def __init__(self, key):
      self.SECRET_KEY = str(key).encode("utf-8")
      self.BLOCK_SIZE = 32 # Bytes
      self.CIPHER = AES.new(self.SECRET_KEY, AES.MODE_ECB) # never use ECB in strong systems obviously

    def encrypt(self, text):
       text = str(text).encode("utf-8")
       return base64.b64encode(self.CIPHER.encrypt(pad(text, self.BLOCK_SIZE))).decode("utf-8")
    
    def decrypt(self, encoded_text):
       self.CIPHER = AES.new(self.SECRET_KEY, AES.MODE_ECB)
       return unpad(self.CIPHER.decrypt(base64.b64decode(encoded_text)), self.BLOCK_SIZE).decode("utf-8")
       
cryptor = Cryptor("1234567890123456")
text = "hello world"
text = cryptor.encrypt(text)
print(text)
print(cryptor.decrypt(text))

Upvotes: 1

Abhishake Gupta
Abhishake Gupta

Reputation: 3170

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))

Upvotes: 15

Related Questions