sign($this->getSignContent($params), $privateKey, $signType);
}
public function rsaSign($params, $privateKey, $signType = "RSA")
{
return $this->sign($this->getSignContent($params), $privateKey, $signType);
}
function unicodeDecode($name)
{
$json = '{"str":"' . $name . '"}';
$arr = json_decode($json, true);
if (empty($arr)) return '';
return $arr['str'];
}
public function getSignContent($params)
{
ksort($params);
$stringToBeSigned = "";
foreach ($params as $k => $v) {
$isarray = is_array($v);
if ($isarray) {
$stringToBeSigned .= "$k" . "=" . json_encode($v, 320) . "&";
} else {
$stringToBeSigned .= "$k" . "=" . "$v" . "&";
}
}
unset ($k, $v);
$stringToBeSigned = substr($stringToBeSigned, 0, strlen($stringToBeSigned) - 1);
return $stringToBeSigned;
}
protected function sign($data, $rsaPrivateKey, $signType = "RSA")
{
$res = "-----BEGIN RSA PRIVATE KEY-----\n" .
wordwrap($rsaPrivateKey, 64, "\n", true) .
"\n-----END RSA PRIVATE KEY-----";
($res) or die('您使用的私钥格式错误,请检查RSA私钥配置');
if ("RSA2" == $signType) {
openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA256);
} else {
openssl_sign($data, $sign, $res);
}
$sign = base64_encode($sign);
return $sign;
}
//废弃
protected function signold($data, $signType = "RSA")
{
if ($this->checkEmpty($this->rsaPrivateKeyFilePath)) {
$priKey = $this->rsaPrivateKey;
$res = "-----BEGIN RSA PRIVATE KEY-----\n" .
wordwrap($priKey, 64, "\n", true) .
"\n-----END RSA PRIVATE KEY-----";
} else {
$priKey = file_get_contents($this->rsaPrivateKeyFilePath);
$res = openssl_get_privatekey($priKey);
}
($res) or die('您使用的私钥格式错误,请检查RSA私钥配置');
if ("RSA2" == $signType) {
openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA256);
} else {
openssl_sign($data, $sign, $res);
}
if (!$this->checkEmpty($this->rsaPrivateKeyFilePath)) {
openssl_free_key($res);
}
$sign = base64_encode($sign);
return $sign;
}
public function curl($url, $postBodyString = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$encodeArray = Array();
$postMultipart = false;
//echo $postBodyString;
unset ($k, $v);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postBodyString);
$this->writeLog("postBodyString" . $postBodyString);
$headers = array('content-type:application/json;charset=' . $this->postCharset);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$reponse = curl_exec($ch);
//echo "reponse".$reponse;
if (curl_errno($ch)) {
throw new Exception(curl_error($ch), 0);
} else {
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (200 !== $httpStatusCode) {
throw new Exception($reponse, $httpStatusCode);
}
}
curl_close($ch);
return $reponse;
}
protected function getMillisecond()
{
list($s1, $s2) = explode(' ', microtime());
return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
}
//请确保项目文件有可写权限,不然打印不了日志。
function writeLog($text)
{
// $text=iconv("GBK", "UTF-8//IGNORE", $text);
//$text = characet ( $text );
file_put_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . "../log.txt", date("Y-m-d H:i:s") . " " . $text . "\r\n", FILE_APPEND);
}
/**
* 转换字符集编码
* @param $data
* @param $targetCharset
* @return string
*/
function characet($data, $targetCharset)
{
if (!empty($data)) {
$fileType = $this->fileCharset;
if (strcasecmp($fileType, $targetCharset) != 0) {
$data = mb_convert_encoding($data, $targetCharset, $fileType);
// $data = iconv($fileType, $targetCharset.'//IGNORE', $data);
}
}
return $data;
}
/**
* 校验$value是否非空
* if not set ,return true;
* if is null , return true;
**/
protected function checkEmpty($value)
{
if (!isset($value))
return true;
if ($value === null)
return true;
if (trim($value) === "")
return true;
return false;
}
/** rsaCheckV1 & rsaCheckV2
* 验证签名
* 在使用本方法前,必须初始化AopClient且传入公钥参数。
* 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
**/
public function rsaCheckV1($params, $rsaPublicKeyFilePath, $signType = 'RSA')
{
$sign = $params['sign'];
$params['sign_type'] = null;
$params['sign'] = null;
return $this->verify($this->getSignContent($params), $sign, $rsaPublicKeyFilePath, $signType);
}
public function rsaCheckV2($params, $rsaPublicKeyFilePath, $signType = 'RSA')
{
$sign = $params['sign'];
$params['sign'] = null;
return $this->verify($this->getSignContent($params), $sign, $rsaPublicKeyFilePath, $signType);
}
function verify($paramStr, $sign,$rsaPublicKey)
{
// $pubKey = $this->$rsaPublicKey;
//将字符串格式公私钥转为pem格式公私钥
$pubKeyPem = $this->format_secret_key($rsaPublicKey, 'pub');
//转换为openssl密钥,必须是没有经过pkcs8转换的公钥
$res = openssl_get_publickey($pubKeyPem);
//url解码签名
//$signUrl = urldecode($sign);
//base64解码签名
$signBase64 = base64_decode($sign);
//调用openssl内置方法验签,返回bool值
$result = (bool)openssl_verify($paramStr, $signBase64, $res);
//释放资源
openssl_free_key($res);
//返回资源是否成功
return $result;
}
function format_secret_key($secret_key, $type)
{
// 64个英文字符后接换行符"\n",最后再接换行符"\n"
$key = (wordwrap($secret_key, 64, "\n", true)) . "\n";
// 添加pem格式头和尾
if ($type == 'pub') {
$pem_key = "-----BEGIN PUBLIC KEY-----\n" . $key . "-----END PUBLIC KEY-----\n";
} else if ($type == 'pri') {
$pem_key = "-----BEGIN RSA PRIVATE KEY-----\n" . $key . "-----END RSA PRIVATE KEY-----\n";
} else {
echo('公私钥类型非法');
exit();
}
return $pem_key;
}
public function checkSignAndDecrypt($params, $rsaPublicKeyPem, $rsaPrivateKeyPem, $isCheckSign, $isDecrypt)
{
$charset = $params['charset'];
$bizContent = $params['biz_content'];
if ($isCheckSign) {
if (!$this->rsaCheckV2($params, $rsaPublicKeyPem)) {
echo "
checkSign failure
";
exit;
}
}
if ($isDecrypt) {
return $this->rsaDecrypt($bizContent, $rsaPrivateKeyPem, $charset);
}
return $bizContent;
}
public function encryptAndSign($bizContent, $rsaPublicKeyPem, $rsaPrivateKeyPem, $charset, $isEncrypt, $isSign)
{
// 加密,并签名
if ($isEncrypt && $isSign) {
$encrypted = $this->rsaEncrypt($bizContent, $rsaPublicKeyPem, $charset);
$sign = $this->sign($bizContent);
$response = "
" . openssl_error_string() . "
";
}
$encodes[] = $chrtext ;
}
$chrtext = implode(",", $encodes);
return $chrtext;
}
public function rsaDecrypt($data, $rsaPrivateKeyPem, $charset)
{
//读取私钥文件
$priKey = file_get_contents($rsaPrivateKeyPem);
//转换为openssl格式密钥
$res = openssl_get_privatekey($priKey);
$decodes = explode(',', $data);
$strnull = "";
$dcyCont = "";
foreach ($decodes as $n => $decode) {
if (!openssl_private_decrypt($decode, $dcyCont, $res)) {
echo "
" . openssl_error_string() . "
";
}
$strnull .= $dcyCont;
}
return $strnull;
}
function splitCN($cont, $n = 0, $subnum, $charset)
{
//$len = strlen($cont) / 3;
$arrr = array();
for ($i = $n; $i < strlen($cont); $i += $subnum) {
$res = $this->subCNchar($cont, $i, $subnum, $charset);
if (!empty ($res)) {
$arrr[] = $res;
}
}
return $arrr;
}
function subCNchar($str, $start = 0, $length, $charset = "gbk")
{
if (strlen($str) <= $length) {
return $str;
}
$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
preg_match_all($re[$charset], $str, $match);
$slice = join("", array_slice($match[0], $start, $length));
return $slice;
}
function parserResponseSubCode($request, $responseContent, $respObject, $format)
{
if ("json" == $format) {
$apiName = $request->getApiMethodName();
$rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
$errorNodeName = $this->ERROR_RESPONSE;
$rootIndex = strpos($responseContent, $rootNodeName);
$errorIndex = strpos($responseContent, $errorNodeName);
if ($rootIndex > 0) {
// 内部节点对象
$rInnerObject = $respObject->$rootNodeName;
} elseif ($errorIndex > 0) {
$rInnerObject = $respObject->$errorNodeName;
} else {
return null;
}
// 存在属性则返回对应值
if (isset($rInnerObject->sub_code)) {
return $rInnerObject->sub_code;
} else {
return null;
}
} elseif ("xml" == $format) {
// xml格式sub_code在同一层级
return $respObject->sub_code;
}
}
function parserJSONSignData($request, $responseContent, $responseJSON)
{
$signData = new SignData();
$signData->sign = $this->parserJSONSign($responseJSON);
$signData->signSourceData = $this->parserJSONSignSource($request, $responseContent);
return $signData;
}
function parserJSONSignSource($request, $responseContent)
{
$apiName = $request->getApiMethodName();
$rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
$rootIndex = strpos($responseContent, $rootNodeName);
$errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
if ($rootIndex > 0) {
return $this->parserJSONSource($responseContent, $rootNodeName, $rootIndex);
} else if ($errorIndex > 0) {
return $this->parserJSONSource($responseContent, $this->ERROR_RESPONSE, $errorIndex);
} else {
return null;
}
}
function parserJSONSource($responseContent, $nodeName, $nodeIndex)
{
$signDataStartIndex = $nodeIndex + strlen($nodeName) + 2;
$signIndex = strpos($responseContent, "\"" . $this->SIGN_NODE_NAME . "\"");
// 签名前-逗号
$signDataEndIndex = $signIndex - 1;
$indexLen = $signDataEndIndex - $signDataStartIndex;
if ($indexLen < 0) {
return null;
}
return substr($responseContent, $signDataStartIndex, $indexLen);
}
function parserJSONSign($responseJSon)
{
return $responseJSon->sign;
}
function parserXMLSignData($request, $responseContent)
{
$signData = new SignData();
$signData->sign = $this->parserXMLSign($responseContent);
$signData->signSourceData = $this->parserXMLSignSource($request, $responseContent);
return $signData;
}
function parserXMLSignSource($request, $responseContent)
{
$apiName = $request->getApiMethodName();
$rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
$rootIndex = strpos($responseContent, $rootNodeName);
$errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
// $this->echoDebug("
rootNodeName:" . $rootNodeName);
// $this->echoDebug("
responseContent: