Given final block not properly padded. Such issues can arise if a bad key is used during decryption - AES encryption using pycryptodome

325 views Asked by At

I am using the following class to encode and decode, it works without issues when pass the encrypted string directly from the encrypt function to the decrypt function. But if I try to decrypt the encrypted string using online decryption it throws this error and the same happens if I try to decrypt a encrypted string from an external source.

class AESCipher(object):
    def __init__(self, key):
        self.bs = AES.block_size
        self.key = bytes.fromhex(key)

    def encrypt(self, raw):
        raw = pad(raw.encode('utf-8'), AES.block_size)
        cipher = AES.new(self.key, AES.MODE_ECB)
        encrypted_data = cipher.encrypt(raw)
        return encrypted_data.hex()

    def decrypt(self, enc):
        enc = bytes.fromhex(enc)
        cipher = AES.new(self.key, AES.MODE_ECB)
        decrypted_data = cipher.decrypt(enc)
        return decrypted_data

I tried using different types of .hex and encoding and decoding, but all had the same result.

1

There are 1 answers

1
Swaraj Kausik On

Replacing bytes.fromhex(key) with bytes(key, "utf-8") solved the issue.