I got a little problem regarding AES decryption. I have to decrypt some text that has been encrypted using 128bit AES / ECB with PHP mcrypt. The thing is, the key that is being used to encrypt/decrypt is 32 bytes long instead of 16. This is all good when I encrypt/decrypt through mcrypt, but now I have to write a decrypt function in another language (LUA). The problem I have is that the library I'm using in LUA doesn't support keys longer than 16 bytes, it has to be exactly 16 bytes long. I guess that mcrypt internally transforms keys longer than 16 bytes into a 16 byte form, but I don't know how. What I'm trying to do is to do the exact same key transformation in LUA so my library can decrypt it. Changing the key is a no go, as it was given by a service provider. Here's the PHP code that does the encrypt/decrypt:

function aes_encrypt($sStr, $sKey = "12345678901234561234567890123456") {
    return base64_encode(mcrypt_encrypt(

function aes_decrypt($sStr, $sKey = "12345678901234561234567890123456") {
    $str =  rtrim(mcrypt_decrypt(
   return preg_replace("/[^\d]/", "", $str); 

Any help is much appreciated.

  • 4
    NEVER USE ECB MODE! NEVER!! I shouted that on purpose. It needs to be shouted. If this is required by the same provider, then I'd go back an demand quite strongly that they use a secure mode of operation instead. Or chose a different, competent provider instead, if that's an option.
    – Xander
    Nov 13, 2014 at 16:10
  • @Xander Yes I know about ECB. But I'm not the one that sets the requirements, the provider does. They use ECB for encrypting, so that's about it. I'm afraid I'm just a code monkey, I can't make any demand :P
    – Tidesson
    Nov 13, 2014 at 16:23

1 Answer 1

  1. 128bit AES has 128 bit keys by definition. If the key is 32 bytes, it's AES-256.
  2. Perhaps your key consists of 32 hex characters, which only map to 16 bytes or 128 bits.
  3. Note that all variants of AES, map to MCRYPT_RIJNDAEL_128 in php, since that 128 is the block size and AES has 128 bit blocks regardless of the key size.
  4. As Xander said, your code it very weak since it uses ECB mode. Use authenticated encryption instead.
  • 1
    Thanks CodesInChaos. No, the key is not hexadecimal; but you're right, it was AES-256. The MCRYPT_RIJNDAEL_128 confused me. I tried decrypting with 256 bit AES and it worked. Thanks!
    – Tidesson
    Nov 13, 2014 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.