我试图在Python3中模仿http://www.hanewin.net/encrypt/aes/aes-test.htm的Rijndael(AES)加密。
具体来说,当我使用以下输入时:
Key in hex = AAAABBBBCCCCDDDDEEEEFFFF00001111
Plaintext in hex = 11112222333344445555666677778888
我希望输出为:
Ciphertext in hex = ec151e51fc722c06073928d17fa4f6da
通过查看网页的源代码,它正在使用ECB。我已经安装了PyCrypto并按照加密示例进行了加密,这就是我所得到的:
>>> from Crypto.Cipher import AES
>>>
>>> KEY = 'AAAABBBBCCCCDDDDEEEEFFFF00001111'
>>> rijn = AES.new(KEY, AES.MODE_ECB)
>>> plaintext = '11112222333344445555666677778888'
>>> ciphertext = rijn.encrypt(plaintext)
>>> ciphertext
b'\xf8Gy\x17\x85$\xf4?\xd3}\x91\xa1\xad\xab\xa1\x07g\xf7P\xd4:\x7f\xc0\x18m)\rTu,\xd0\xa2'
所以我的密文就是长二进制字符串(如果这是正确的术语)。假设所有设置都是正确的,它应该相当于ec151e51fc722c06073928d17fa4f6da
。如何将b'\xf8Gy\x17\x85$\xf4?\xd3}\x91\xa1\xad\xab\xa1\x07g\xf7P\xd4:\x7f\xc0\x18m)\rTu,\xd0\xa2'
转换为ec151e51fc722c06073928d17fa4f6da
?
更新: 根据Jon在评论中提出的建议,我已经导入了binascci,现在我得到了以下输出:
>>> import binascii
>>>
>>> binascii.hexlify(ciphertext)
b'f84779178524f43fd37d91a1adaba10767f750d43a7fc0186d290d54752cd0a2'
所以它可能仍然是我有正确的密码,但转换中有些不同。以下是网页源代码的摘录:
theForm.ciphertext.value = byteArrayToHex(rijndaelEncrypt(pt, key, "ECB"));
// This function takes an array of bytes (byteArray) and converts them
// to a hexadecimal string. Array element 0 is found at the beginning of
// the resulting string, high nibble first. Consecutive elements follow
// similarly, for example [16, 255] --> "10ff". The function returns a
// string.
function byteArrayToHex(byteArray) {
var result = "";
if (!byteArray)
return;
for (var i=0; i<byteArray.length; i++)
result += ((byteArray[i]<16) ? "0" : "") + byteArray[i].toString(16);
return result;
}
答案 0 :(得分:1)
如上所述,以下是评论者帮助达成的答案:
>>> from Crypto.Cipher import AES
>>> import binascii
>>> KEY = binascii.unhexlify('AAAABBBBCCCCDDDDEEEEFFFF00001111')
>>> plaintext = binascii.unhexlify('11112222333344445555666677778888')
>>> rijn = AES.new(KEY, AES.MODE_ECB)
>>> ciphertext = rijn.encrypt(plaintext)
>>> binascii.hexlify(ciphertext)
b'ec151e51fc722c06073928d17fa4f6da'
>>> print(binascii.hexlify(ciphertext).decode('utf-8'))
ec151e51fc722c06073928d17fa4f6da