Using a byte array as key for AES algorithm in Python

倖福魔咒の 提交于 2019-12-10 17:56:52

问题


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,


回答1:


Apparently this does the trick:

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

It looks pretty obvious now, doesn't it?



来源:https://stackoverflow.com/questions/40180779/using-a-byte-array-as-key-for-aes-algorithm-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!