PHP-Openssl_decrypt错误:错误的最终块长度(AES 256 CBC模式加密/解密) [英] PHP - Openssl_decrypt error : wrong final block length (AES 256 CBC mode encryption/decryption)
问题描述
这是我的代码:
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();
}
我使用swift / android进行加密,并使用php进行解密。
I encrypt using swift/android and i decrypt using php.
openssl_error_string()方法返回错误:0606506D:数字信封例程:EVP_DecryptFinal_ex:错误的最终块长度。
The openssl_error_string() method return "error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length".
请注意,加密swift / android中的密钥和iv相同。
我在这里找不到问题。任何人?谢谢。
Note that the key and iv in encryption swift/android are the same. I cant find the problem here. Anyone? Thanks.
推荐答案
我解决了这个问题。事实是我是Android端的URLEncoding参数,然后用我的PHP脚本进行URLDecoding。
I solve the problem. The fact is that i am URLEncoding params on Android side, and then URLDecoding them with my PHP script.
不幸的是, +的URL解码在Android,但在ios中是正确的('+')。
Unfortunately, the URL decoding of a '+' is a whitespace in Android but in ios it is correct ('+').
因此在PHP方面,在解码之前,我用'+'替换了空白字符。
然后删除base64_decode函数。
So on PHP side i substituted the whitespace character with '+' before Decoding. And i remove the base64_decode function.
更新后的代码:
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;
}
这篇关于PHP-Openssl_decrypt错误:错误的最终块长度(AES 256 CBC模式加密/解密)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!