PHP - Openssl_decrypt error : wrong final block le

2019-08-15 07:26发布

问题:

This is my code :

 function decrypt($code)
{

    $key = '3552ef55ecdf04324..'; // 64 bytes length
    $iv = 'd20818af907b59c3b15d258dd3969770'; // 32 bytes length
    $key = hash("sha256", $key,true); // 32 bytes length
    $iv = md5($iv,true); // 16 bytes length

    echo strlen(base64_decode($code)); // 80 bytes
   //return openssl_decrypt(base64_decode($code), 'aes-256-cbc', $key, 0 ,$iv); // return false
    $output = openssl_decrypt(base64_decode($code), 'aes-256-cbc', $key, 0 ,$iv);
    return openssl_error_string(); 

}

I encrypt using swift/android and i decrypt using php.

The openssl_error_string() method return "error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length".

Note that the key and iv in encryption swift/android are the same. I cant find the problem here. Anyone? Thanks.

回答1:

I solve the problem. The fact is that i am URLEncoding params on Android side, and then URLDecoding them with my PHP script.

Unfortunately, the URL decoding of a '+' is a whitespace in Android but in ios it is correct ('+').

So on PHP side i substituted the whitespace character with '+' before Decoding. And i remove the base64_decode function.

Updated code:

  function decrypt($code)
{

$key = '3552ef55ecdf04324d0fe72343...';
$iv  = 'd20818af907b59c3b15d258dd3969770';

$key = hash("sha256", $key, true);
$iv  = md5($iv, true);
if (preg_match('/\s/', trim($code))) {
    $code = str_replace(' ', '+', trim($code));
}

$output = openssl_decrypt($code, 'aes-256-cbc', $key, 0, $iv);
return $output;

}