0

I have some python code,

 hash_object = hashlib.sha256(b'Hello World')
 hex_dig = hash_object.hexdigest()

 cipher = AES.new(hex_dig, AES.MODE_CBC, iv)
 plain = cipher.decrypt( cipher )

but, I have an error - ValueError: AES key must be either 16, 24, or 32 bytes long

But, I want 32bytes key, not 16bytes key. I don't know why hash_val=hashfct.digest() is not 32bytes Also, I tried "hash_val=hashfct.digest()[0:32]" but it is not work, too.

How can I get the 32byte long key?

Thanks.

eneski
  • 1,575
  • 17
  • 40
khi0227
  • 11
  • 1
  • 5

2 Answers2

1

You should really consider a proper key derivation algorithm instead of rolling your own. PBKDF2 is one of the more common algorithms that should protect you from some of the usual mistakes. For example, in your case, it is very easy to brute force the password because you only have one round of hashing.

Here is some modified sample code from hashlib:

>>> import hashlib
>>> dk = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000)
>>> dk[:32]
b'\x03\x94\xa2\xed\xe32\xc9\xa1>\xb8.\x9b$c\x16\x04\xc3\x1d\xf9x\xb4\xe2\xf0\xfb\xd2\xc5I\x94O\x9dy\xa5'

You should also make sure b'salt' is random and different every time you generate a new key. For a cryptographically secure random function in Python, see How can I create a random number that is cryptographically secure in python?

This is for Python 3, but should be simple enough to adjust for Python 2.

Community
  • 1
  • 1
kichik
  • 33,220
  • 7
  • 94
  • 114
0

you need to use the digest method

hash_object = hashlib.sha256(b'Hello World')
hex_dig = hash_object.digest()

cipher = AES.new(hex_dig, AES.MODE_CBC, iv)
plain = cipher.decrypt( cipher )

I really don't know the reason but this works, because I had the same problem.

BrokenBinary
  • 7,731
  • 3
  • 43
  • 54
eneski
  • 1,575
  • 17
  • 40