ValueError: AES key must be 16, 24 or 32 bytes long

This piece of code worked and then started with an error

ValueError: AES key must be 16, 24 or 32 bytes long

This is in Python 3.3.5.

from Crypto.Cipher import AES

salt = '!%F=-?Pst970'
key32 = [ ' ' if i >= len(self.salt) else self.salt[i] for i in range(32) ]
bkey32 = str(key32).encode('utf-8')

cipher = AES.new(bkey32, AES.MODE_ECB)

The AES constructor fails with the ValueError specified in the header.

bkey32:

b"['!', '%', 'F', '=', '-', '?', '\\x7f', 'P', 's', 't', '9', '7', '0', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']"

I believe this is 32 bytes. What am I doing wrong?

+4
source share
2 answers

You create a view of stryour list, you need the joincontents of the list:

key32 = "".join([ ' ' if i >= len(salt) else salt[i] for i in range(32) ])
bkey32 = key32.encode('utf-8')

str.join creates one concatenated line:

In [19]: "".join([ ' ' if i >= len(salt) else salt[i] for i in range(32) ])
Out[19]: '!%F=-?Pst970           

Or use str.format:

salt = '!%F=-?Pst970'
key32 = "{: <32}".format(salt).encode("utf-8")
cipher = AES.new(key32, AES.MODE_ECB)
+3
source

str ; [, ], .

bytes.ljust, 32 :

salt = b'!%F=-?Pst970'
bkey32 = salt.ljust(32)[:32]   # [:32] is unnecessary if you're sure `salt` is less than 32
# bkey32 => b'!%F=-?Pst970                    '
+2

Source: https://habr.com/ru/post/1620364/


All Articles