Search code examples
phpc++mcryptcrypto++

Crypto++ to PHP mcrypt not working


I have a C++ application that's using Crypto++ to send encrypted data to a PHP site. However, when the data's getting to the PHP side, it's not decrypting the data properly.

The C++ / Crypto++ code:

char stupidKey[AES::MAX_KEYLENGTH] = "thisisastupidkeythisisastupidke";

ECB_Mode<AES>::Encryption aes((byte *)stupidKey, AES::MAX_KEYLENGTH);

std::string cypher;
StringSource(aData, true, new StreamTransformationFilter(aes, new StringSink( cypher ))); 
StringSource(cypher, true, new Base64Encoder( new StringSink(aOutput) ));

The PHP Code:

define('CRYPT_SECRET', 'thisisastupidkeythisisastupidke');

$postData = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, 
                CRYPT_SECRET, base64_decode($_POST['request']), 
                MCRYPT_MODE_ECB);

Note: I know ECB is a bad choice of encryption mode, but I'd like to get this working without the added oddities of the IV first, then complicate matters.


Solution

  • Looking at the PHP manual (http://php.net/manual/en/function.mcrypt-decrypt.php), MCRYPT_RIJNDAEL_256 is different to AES_256. The first comment offers some help: http://www.php.net/manual/en/function.mcrypt-decrypt.php#105985

    Caution, MCRYPT_RIJNDAEL_256 is not equivalent to AES_256.

    The way to make RIJNDAEL be decrypted from AES with openssl is to use MCRYPT_RIJNDAEL_128 and padd the string to encrypt before encrypting with the follwing function:

    <?php 
    function pkcs5_pad ($text, $blocksize) { 
        $pad = $blocksize - (strlen($text) % $blocksize); 
        return $text . str_repeat(chr($pad), $pad); 
    } 
    ?> 
    

    On the decryption, the choosing of AES_256 or AES_128, etc. is based on the keysize used in the crypting. In my case it was a 128bit key so I used AES_128.