php7.2后解密微信推送过来的数据

目前解密微信推送过来的数据,微信给的demo 还是使用的mcrypt 。但是这个mcrypt 在php 7.2后已经被删除了。需要用openssl来替换进行加解密。网上的资料比较少,一下是我的解决方案

原来的解密函数

public function decrypt($encrypted, $appid)
{

try {
//使用BASE64对需要解密的字符串进行解码
$ciphertext_dec = base64_decode($encrypted);
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
$iv = substr($this->key, 0, 16);
mcrypt_generic_init($module, $this->key, $iv);

//解密
$decrypted = mdecrypt_generic($module, $ciphertext_dec);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
} catch (Exception $e) {
return array(ErrorCode::$DecryptAESError, null);
}


try {
//去除补位字符
$pkc_encoder = new PKCS7Encoder;
$result = $pkc_encoder->decode($decrypted);
//去除16位随机字符串,网络字节序和AppId
if (strlen($result) < 16)
return "";
$content = substr($result, 16, strlen($result));
$len_list = unpack("N", substr($content, 0, 4));
$xml_len = $len_list[1];
$xml_content = substr($content, 4, $xml_len);
$from_appid = substr($content, $xml_len + 4);
} catch (Exception $e) {
//print $e;
return array(ErrorCode::$IllegalBuffer, null);
}
if ($from_appid != $appid)
return array(ErrorCode::$ValidateAppidError, null);
return array(0, $xml_content);

}

替换后的解密函数

public function decrypt($encrypted, $appid)
{
try {

// 确保 IV 为 16 字节,使用密钥的前 16 字节
$iv = substr(trim($this->key), 0, 16);


$decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $this->key, OPENSSL_ZERO_PADDING, $iv);

if ($decrypted === false) {
throw new Exception('Decryption failed');
}

} catch (Exception $e) {
return array(self::$DecryptAESError, null);
}

try {
// 去除补位字符
$result = self::decode($decrypted);

print_r($result);exit;

// 去除16位随机字符串, 网络字节序和AppId
if (strlen($result) < 16) {
return array(ErrorCode::$IllegalBuffer, null);
}

$content = substr($result, 16, strlen($result));
$len_list = unpack("N", substr($content, 0, 4));
$xml_len = $len_list[1];
$xml_content = substr($content, 4, $xml_len);
$from_appid = substr($content, $xml_len + 4);

} catch (Exception $e) {
return array(ErrorCode::$IllegalBuffer, null);
}

if ($from_appid != $appid) {
return array(self::$ValidateAppidError, null);
}

return array(0, $xml_content);
}

需要注意的点是微信推送过来的数据加密位数是256  也就是这个AES-256-CBC。所以$this->key 不需要换,之需要用以前代码就可以。$encrypted 这个数据源代码是 $ciphertext_dec = base64_decode($encrypted);经过base64 decode的,这个地方,一定要删除,直接用微信解析出来的postdata 就行。你如果base64 decode了就解码不了了。如果你也在迷茫这个解码,直接复制我的代码就可以解决。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值