Python Incorrect AES key length despite passing the a 32 bytes bytearray

Question:

I have a specific AES key that I have to work with which is 11h,FFh,E4h,"I",BCh,D4h,96h,"SRZ",BEh,B2h,BEh,D0h,89h,E6h,EBh,91h,92h,"f",FCh,"#",BBh,F8h,"hn",8Dh,"Y",19h,"g",8Ah,"Q"

I have to use this key to encrypt a message. In python I covert it to "x11,xFF,xE4,I,xBC,xD4,x96,SRZ,xBE,xB2,xBE,xD0,x89,xE6,xEB,x91,x92,f,xFC,#,xBB,xF8,hn,x8D,Y,x19,g,x8A,Q" but I get ValueError: Incorrect AES key length (60 bytes).

I tried encoding the key in a different way like key = bytearray("x11xFFxE4IxBCxD4x96SRZxBExB2xBExD0x89xE6xEBx91x92fxFC#xBBxF8hnx8DYx19gx8AQ".encode('utf-8')) but I still get a same key length error.

What can I do in this case?

This is my code:

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

msg = "<mes><action type="key-update"/></mes>".zfill(216) 
key = bytearray("x11xFFxE4IxBCxD4x96SRZxBExB2xBExD0x89xE6xEBx91x92fxFC#xBBxF8hnx8DYx19gx8AQ".encode('utf-8'))

print(key)

cipher = AES.new(key, AES.MODE_GCM)
encrypted_msg = cipher.encrypt(msg)
print(encrypted_msg)
Asked By: Eimanalw

||

Answers:

How about using bytes instead?

#pip install pycryptodome
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

msg = b"<mes><action type="key-update"/></mes>".zfill(216) 
key = bytearray(b"x11xFFxE4IxBCxD4x96SRZxBExB2xBExD0x89xE6xEBx91x92fxFC#xBBxF8hnx8DYx19gx8AQ")

print(key)

cipher = AES.new(key, AES.MODE_GCM)
encrypted_msg = cipher.encrypt(msg)
print(encrypted_msg)

This seems to be working.
Please note that you can also use bytes.fromhex, which is more readable

#pip install pycryptodome
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

msg = b"<mes><action type="key-update"/></mes>".zfill(216) 
key = bytearray(bytes.fromhex("11ffe449bcd49653525abeb2bed089e6eb919266fc23bbf8686e8d5919678a51"))

print(key)

cipher = AES.new(key, AES.MODE_GCM)
encrypted_msg = cipher.encrypt(msg)
print(encrypted_msg)

Now, the good question: why does this happen?
Well, utf-8 encodes the non ascii characters differently, pseudocode:

 "x11xFF    xE4    IxBC    xD4    x96    SRZxBE    xB2    xBE    xD0    x89    xE6    xEB    x91    x92    fxFC    #xBB    xF8    hnx8D    Yx19gx8A    Q".encode('utf-8')
b'x11xc3xbfxc3xa4Ixc2xbcxc3x94xc2x96SRZxc2xbexc2xb2xc2xbexc3x90xc2x89xc3xa6xc3xabxc2x91xc2x92fxc3xbc#xc2xbbxc3xb8hnxc2x8dYx19gxc2x8aQ'
Answered By: Nineteendo