$xmlResult = file_get_contents("php://input");//获取微信的数据
$result = $this->xmlToArray($xmlResult);//将xml转成数组
// 将加密的数据解密,方法在下面
$reqInfo = $this->refund_decrypt($result['req_info']);
/** 退款通知解密* @Author WangZhaoBo* @param $str 微信同步的加密串req_info* @param $key 商户key*/ public function refund_decrypt($str) {$key = md5($this->appSecret);$str = base64_decode($str);$str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB);$block = mcrypt_get_block_size('rijndael_128', 'ecb');$pad = ord($str[($len = strlen($str)) - 1]);$len = strlen($str);$pad = ord($str[$len - 1]);return substr($str, 0, strlen($str) - $pad); }
//SHA256签名
/*** 作用:生成256签名*/public function get256Sign($Obj,$key = null){foreach ($Obj as $k => $v){$Parameters[$k] = $v;}//签名步骤一:按字典序排序参数 ksort($Parameters);$String = $this->formatBizQueryParaMap($Parameters, false);//echo '【string1refund_decrypt】'.$String.'</br>';//签名步骤二:在string后加入KEYif(is_null($key)){$key = WxPayConf_pub::$KEY;$String = $String."&key=".WxPayConf_pub::$KEY;}else{$String = $String."&key=".$key;}echo $String;//签名步骤三:MD5加密//$String = md5($String);$String = hash_hmac("sha256", $str, $key);//echo "【string3】 ".$String."</br>";//签名步骤四:所有字符转为大写$result_ = strtoupper($String);//echo "【result】 ".$result_."</br>";return $result_;}
AEAD_AES_256_GCM的解密php示例代码 (参考:https://pay.weixin.qq.com/wiki/doc/api/xiaowei.php?chapter=19_11和https://blog.csdn.net/u010324331/article/details/82153067和https://pay.weixin.qq.com/wiki/doc/api/download/wxpay_xiaowei_cert.pdf和)
//region 证书解密start public function decodePem(){$ciphertext = '加密后的证书内容';$nonce = '加密证书的随机串,加密证书的随机串';$associated_data = '加密证书的随机串,固定值: certificate';$key = '你的APIv3密钥';$check_sodium_mod = extension_loaded('sodium');if($check_sodium_mod === false){echo '没有安装sodium模块';die;}$check_aes256gcm = sodium_crypto_aead_aes256gcm_is_available();if($check_aes256gcm === false){echo '当前不支持aes256gcm';die;}$pem = sodium_crypto_aead_aes256gcm_decrypt(base64_decode($ciphertext),$associated_data,$nonce,$key);var_dump($pem); //这是解密出来的证书内容,复制出来保存就行了 }//endregion 证书解密end
使用sodium_crypto_aead_aes256gcm_decrypt函数需要安装sodium扩展,要求PHP版本必须大于7,小于7的也有这个扩展, 但是没有sodium_crypto_aead_aes256gcm_decrypt这个方法.
安装sodium扩展方法看这里https://blog.csdn.net/u010324331/article/details/82153067
如果不安装扩展,怎么办? 用paragonie/sodium_compat这个类库.
Sodium Compat 是用于 Sodium 加密库(libsodium)的纯 PHP 填充,它是 PHP 7.2.0+ 的核心扩展,也可用于 PECL。
这个库 tentativeley 支持PHP 5.2.4 - 7.x(最新版),但官方只支持非 EOL 版本的 PHP。
如果安装了 PHP 扩展,Sodium Compat 将机会性地透明地使用 PHP 扩展而不是我们的实现。
github 地址: https://github.com/paragonie/sodium_compat
其中ParagonIE_Sodium_Compat类下面有一个crypto_aead_aes256gcm_decrypt方法.
调用方法
ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_decrypt($ciphertext,$associated_data,$nonce,$key);