PHP - Openssl_decrypt error : wrong final block length (AES 256 CBC mode encryption/decryption)

荒凉一梦 提交于 2019-12-12 21:16:24

问题


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;

}


来源:https://stackoverflow.com/questions/37147049/php-openssl-decrypt-error-wrong-final-block-length-aes-256-cbc-mode-encrypt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!