Python Rijndael 加密

标签 python encryption rijndael

我正在尝试模仿 http://www.hanewin.net/encrypt/aes/aes-test.htm 的 Rijndael (AES) 加密在Python3.

具体来说,当我使用以下输入时:

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;
}

最佳答案

正如上面分享的,以下是评论者帮助得出的答案:

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

关于Python Rijndael 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46221650/

相关文章:

python - 检查序列中的 boolean 变量

python - 可变长度替换为 `re.sub()`

python - sqlalchemy - 加入 association_table

android - XML文件加密

delphi - 帮助在 Delphi 2007.Net 中使用 Rijndael 算法

python - 将数据透视表值移动到行

c# - 重定向后验证用户

security - 两次加密是好是坏?

ocaml - 如何进行伽罗华域乘法?

c# - 使用 CryptDecrypt 解密 RijndaelManaged 加密字符串