Search code examples
phpencryptionaespkcs#7ecb

Encryption AES 128


I've been asked at work to implement a request for a simple web service with the following instructions:

AES encryption:
Type: ECB
Size: 128bits
Padding Mode: PKCS7
key: 9b6018215942b2e1da3797d3394779bf

In the docs (just a given example) they say that for the string:

2874838-49

The encryption process must generate:

BEE361962A1802A7BA2AD328DAE8B291

I've been searching a lot for something like this, but none of the solutions (like here, here here, etc...) given helped me achieving the example result given.

This was the last thing I tried now:

function aes128Encrypt($data, $key) {
  $padding = 32 - (strlen($data) % 32);
  $data .= str_repeat(chr($padding), $padding);
  return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_ECB));
}
$data = "2874838-49";
$key = "9b6018215942b2e1da3797d3394779bf";    
echo aes128Encrypt($data, $key); // UdP7dXSTp6b5I986PLL8Gs3qH3rMj0SpQ0te4pP7M44=

Solution

  • The encoding algorithm returns a stream of bytes back to you of encoded data.

    The sample you have doens't provide a base64 encoded variant of the data but a hexadecimal representation.

    In your case, just swap out the base64_encode for bin2hex and the answer should match up.

    function aes128Encrypt($data, $key) {
      $padding = 32 - (strlen($data) % 32);
      $data .= str_repeat(chr($padding), $padding);
      return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_ECB));
    }
    $data = "2874838-49";
    $key = "keyshouldbeplacedhere";    
    echo aes128Encrypt($data, $key);