Search code examples
python-3.xbinarykeyaestypeerror

Receiving a TypeError in trying to create a new AES cipher in Python3


Just installed PyCryptodome in Pycharm. I have 3 lines of code. I'm trying to give a hard iv and key value to the AES function. It throws this:

  File "C:\Users\user\PycharmProjects\CS\venv\lib\site-packages\Crypto\Cipher\AES.py", line 92, in _create_base_cipher
if len(key) not in key_size:
TypeError: object of type 'int' has no len()

Here is my code.

iv = 0x0008739a3043314e614c4b764f234189
key = 0xf188c2f6176502368ab346a0b40f1098ed350c3c46595e998147ab1db9d865b7
cipher = AES.new(key, AES.MODE_CBC, iv)

I've tried converting to binary but then I get an incorrect AES key length (258)

iv = 0x0008739a3043314e614c4b764f234189
biv = bin(iv)
key = 0xf188c2f6176502368ab346a0b40f1098ed350c3c46595e998147ab1db9d865b7
bkey = bin(key)

cipher = AES.new(bkey, AES.MODE_CBC, biv)    


ValueError: Incorrect AES key length (258 bytes)

Solution

  • The key should be in bytes. To convert an integer to bytes:

    key = 0xf188c2f6176502368ab346a0b40f1098ed350c3c46595e998147ab1db9d865b7
    bkey = key.to_bytes(32, 'big')
    >>> bkey
    b'\xf1\x88\xc2\xf6\x17e\x026\x8a\xb3F\xa0\xb4\x0f\x10\x98\xed5\x0c<FY^\x99\x81G\xab\x1d\xb9\xd8e\xb7'
    

    Note that bin() converts an integer to a string, representing the number as a sequence of '0' and '1' characters, which isn't of much use here.