e4rthdog e4rthdog - 6 months ago 21
PHP Question

Decrypt fails if content is only a zero (0) with openssl encrypt decrypt

I am using the following function for encrypt and decrypt of wordpress post content in a WordPress plugin:

public static function afz_encrypt_decrypt( $action, $string ) {
$output = false;

$encrypt_method = "AES-256-CBC";
$secret_key = '12345678901234567890123456789012';
$iv_size = 16;

if ( $action == 'encrypt' ) {
$encrypt_iv = mcrypt_create_iv( $iv_size, MCRYPT_DEV_URANDOM );
$output = openssl_encrypt( $string, $encrypt_method, $secret_key, 0, $encrypt_iv );
$output = base64_encode( $encrypt_iv . $output );
} else if ( $action == 'decrypt' ) {
$decrypt_iv = substr( base64_decode( $string ), 0, $iv_size );
$output = stripslashes( openssl_decrypt( substr( base64_decode( $string ), $iv_size ), $encrypt_method,
$secret_key,
0,
$decrypt_iv ) );
if ( false == $output ) {
$output = $string;
}
}

return $output;
}


The above code fails to decrypt the text if the content is ONLY a zero character!!!

It returns the encoded string that encrypt produced.

Any ideas?

Answer
if ( false == $output ) {
    $output = $string;
}

This checks if the output is "falsy" and if it is it sets $output back to the original encrypted string. "0" is falsy. Replace the check with

if ( false === $output ) {

To check if the output is actually false and not just falsy.

For a better explanation of what is and isn't falsy, see this documentation page.

Comments