Fran Marzoa
Fran Marzoa

Reputation: 4544

Using a byte array as key for AES algorithm in Python

I have a byte array that is a 128 bits AES key and I want to use that one on a Python script to cipher some information using the aforementioned key.

I have the key stored as a hexadecimal string, something like "27821D90D240EA4F56D0E7612396C69E" (obviously this is not the real key, but has the same format).

I have generated a byte array from that key, that is the way I have been using AES keys in other languages (Java, C# and PHP) so far, like this:

AES_KEY = bytearray.fromhex('27821D90D240EA4F56D0E7612396C69E')

That works fine, but then when I try to use it for creating the cipher, it complains that it wants an string in the first parameter:

cipher = AES.new(AES_KEY, AES.MODE_CBC, os.urandom(16));

TypeError: argument 1 must be string or read-only buffer, not bytearray

I have tried to get an string from the byte array instead, as:

AES_KEY = bytearray.fromhex('27821D90D240EA4F56D0E7612396C69E').decode()

or

AES_KEY = bytearray.fromhex('27821D90D240EA4F56D0E7612396C69E').decode('utf-8')

to no avail because there are non-ascii and non-unicode values in that key.

Replacing the key is NOT an option.

Any ideas?

Thanks a lot in advance,

Upvotes: 5

Views: 4463

Answers (1)

Fran Marzoa
Fran Marzoa

Reputation: 4544

Apparently this does the trick:

AES_KEY = str(bytearray.fromhex('27821D90D240EA4F56D0E7612396C69E'))

It looks pretty obvious now, doesn't it?

Upvotes: 5

Related Questions