/**
* 检验消息的真实性,并且获取解密后的明文.
* @param $msgSignature string 签名串,对应URL参数的msg_signature
* @param $timestamp string 时间戳 对应URL参数的timestamp
* @param $nonce string 随机串,对应URL参数的nonce
* @param $postData string 密文,对应POST请求的数据
* @param &$msg string 解密后的原文,当return返回0时有效
* @param $appId string 视频号appid
*
* @return int 成功0,失败返回对应的错误码
*/
public function decryptMPrpcryptsg($msgSignature, $timestamp, $nonce, $postData, &$msg, $appid)
{
$SHIPIN_Token = 'xxxxx';
$SHIPIN_EncodingAESKey = 'xxxxxxxxxxxxxxxxxxxxxxx';
if (strlen($SHIPIN_EncodingAESKey) != 43) {
return false;
}
$array[] = 0;
$array[] = $postData['Encrypt'];
$array[] = $postData['ToUserName'];
$ret = $array[0];
if ($ret != 0) {
return $ret;
}
if ($timestamp == null) {
$timestamp = time();
}
$encrypt = $array[1];
$touser_name = $array[2];
//验证安全签名
$array = $this->ShiPingetSHA1($SHIPIN_Token, $timestamp, $nonce, $encrypt);
$ret = $array[0];
if ($ret != 0) {
return $ret;
}
$signature = $array[1];
if ($signature != $msgSignature) {
return false;
}
$result = $this->ShiPindecrypt($encrypt, $appId,$SHIPIN_EncodingAESKey);
// dump($result);die;
if ($result[0] != 0) {
return $result[0];
}
$msg = $result[1];
return $msg;
}
/**
* 用SHA1算法生成安全签名
* @param string $token 票据
* @param string $timestamp 时间戳
* @param string $nonce 随机字符串
* @param string $encrypt 密文消息
*/
public function ShiPingetSHA1($token, $timestamp, $nonce, $encrypt_msg)
{
//排序
try {
$array = array($encrypt_msg, $token, $timestamp, $nonce);
sort($array, SORT_STRING);
$str = implode($array);
return array(0, sha1($str));
} catch (Exception $e) {
return false;
}
}
/**
* 对密文进行解密
* @param string $encrypted 需要解密的密文
* @return string 解密得到的明文
*/
public function ShiPindecrypt($encrypted, $appid,$key)
{
$key = base64_decode($key . "=");
try {
//使用BASE64对需要解密的字符串进行解码
$ciphertext_dec = base64_decode($encrypted);
$iv = substr($key, 0, 16);
$decrypted = openssl_decrypt($ciphertext_dec, 'AES-256-CBC', $key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv);
} catch (Exception $e) {
return false;
}
try {
//去除补位字符
$result = $this->ShiPindecode($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 false;
}
if ($from_appid != $appid)
return false;
return array(0, $xml_content);
}
/**
* 对解密后的明文进行补位删除
* @param decrypted 解密后的明文
* @return 删除填充补位后的明文
*/
function ShiPindecode($text)
{
$pad = ord(substr($text, -1));
if ($pad < 1 || $pad > 32) {
$pad = 0;
}
return substr($text, 0, (strlen($text) - $pad));
}
微信视频号消息推送api获取解密后的明文(json格式)
于 2023-04-04 15:28:47 首次发布