在Python中使用字节数组作为AES算法的键 [英] Using a byte array as key for AES algorithm in Python

查看:416
本文介绍了在Python中使用字节数组作为AES算法的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字节数组,它是一个128位AES密钥,我想在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.

我将密钥存储为十六进制字符串,类似于 27821D90D240EA4F56D0E7612396C69E(显然这不是真正的密钥,但是具有相同的格式)。

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

我生成了一个那个密钥的字节数组,到目前为止,这就是我一直在使用其他语言(Java,C#和PHP)的AES密钥的方式,就像这样:

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:参数1必须为字符串或只读缓冲区,而不是
bytearray

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()

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

无济于事,因为该键中包含非ASCII和非Unicode值。

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

替换密钥是没有选择的。

Replacing the key is NOT an option.

有什么想法吗?

非常感谢

推荐答案

显然,这可以解决问题:

Apparently this does the trick:

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

现在看起来很明显,不是吗?

It looks pretty obvious now, doesn't it?

这篇关于在Python中使用字节数组作为AES算法的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆