Search code examples
pythonencryptionrijndael

Python Rijndael Encryption


I'm trying to mimic the Rijndael (AES) encryption of http://www.hanewin.net/encrypt/aes/aes-test.htm in Python3.

Specifically, when I use the following inputs:

Key in hex = AAAABBBBCCCCDDDDEEEEFFFF00001111 
Plaintext in hex = 11112222333344445555666677778888 

I want the output to be:

Ciphertext in hex = ec151e51fc722c06073928d17fa4f6da

From looking at the source code of the webpage, it is using ECB. I've installed PyCrypto and followed the examples for encrypting, and this is what I've gotten:

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

So my ciphertext is that long binary string (if that's the right terminology). Assuming all of the settings were correct, it should be the equivalent of ec151e51fc722c06073928d17fa4f6da. How can I convert b'\xf8Gy\x17\x85$\xf4?\xd3}\x91\xa1\xad\xab\xa1\x07g\xf7P\xd4:\x7f\xc0\x18m)\rTu,\xd0\xa2' to ec151e51fc722c06073928d17fa4f6da?

Update: With Jon's suggestion in the comments, I've imported binascci and now I'm getting the following output:

>>> import binascii
>>> 
>>> binascii.hexlify(ciphertext)
b'f84779178524f43fd37d91a1adaba10767f750d43a7fc0186d290d54752cd0a2'

So it may still be that I have the right cipher, but something is different in the conversion. Here are some excerpts from the webpage's source code:

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

Solution

  • As shared above, here is the answer that the commenters helped to arrive at:

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