Search code examples
phpencryptionphp-5.3mcryptphp-5.6

Encrypt decrypt issue with new php version


I have a encrypt function on one of my website which is running on PHP 5.3.29 The function works proper on this version of PHP. The function is:

function encrypt($text) { 
    return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SALT, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)))); 
}

I have another website which is running on PHP 5.6.29. The same function does not return anything on this version. It returns blank.

Similarly I have decrypt function which is also not working on PHP 5.6.29

function decrypt($text) { 
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SALT, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))); 
}

I need to make this function to work on PHP 5.6.29 as my websites are connected via API. I have no idea how I can make this to work. Any help please?


Solution

  • You're probably passing an incorrect value for SALT. From the manual:

    Invalid key and iv sizes are no longer accepted. mcrypt_encrypt() will now throw a warning and return FALSE if the inputs are invalid. Previously keys and IVs were padded with '\0' bytes to the next valid size.

    This was a change made to PHP 5.6, which lines up with what you're seeing.

    Note that an encryption key is not the same as a hashing salt, which can generally be of any length.