<?php
namespace App\Lib;
class UKEY
{
    protected static $url="http://223.70.139.221:18088";
    protected static $appName="SVSDefault";
    public static function GetServerInfo(){
        $info=[];
        $c=[
            'appName'=>self::$appName,
            'length'=>16
        ];
        $random='';
        $res=self::post(self::$url.'/api/common/genRandom',json_encode($c));//获取随机数
        if($res['status']==0){
            $random=$res['body']['random'];
            $info['random']=$random;
            $info['signData']=self::signData($random);
            $info['serverCert']=self::GetServerCert();
        }

      return $info;
    }
    //数据签名
    public static function signData($oriData){
        $c=[
            'appName'=>self::$appName,
            'oriData'=>$oriData
        ];
        $sign='';
        $res=self::post(self::$url.'/api/pkcs1/signData',json_encode($c));
        if($res['status']==0){
            $sign=$res['body']['p1Sign'];
        }
        return $sign;
    }
    //获取服务器证书
    public static function GetServerCert(){
        $c=[
            'appName'=>self::$appName,
        ];
        $cert='';
        $res=self::post(self::$url.'/api/cert/getServerCertificate',json_encode($c));
        if($res['status']==0){
            $cert=$res['body']['base64Cert'];
        }
        return $cert;
    }
    //服务端验证客户端证书有效性,证书有效返回1,证书无效情况下：-1为不是所信任的根，-2为超过
    //有效期，-3为作废证书，-4已加入黑名单，-5证书未生效, 0 未知错误
    public static function CheckCert($cert){
        $c=[
            'appName'=>self::$appName,
            'cert'=>$cert
        ];
        $validRes='';
        $res=self::post(self::$url.'/api/cert/validateCert',json_encode($c));
        if($res['status']==0){
            $validRes=$res['body']['validRes'];
        }
        return $validRes;
    }
    //验证数据签名 返回数据签名验证结果,true 验证通过，false 验证失败
    public static function CheckSign($cert,$oriData,$sign){
        $c=[
            'appName'=>self::$appName,
            'cert'=>$cert,
            'oriData'=>$oriData,
            'sign'=>$sign
        ];
        $validRes=false;
        $res=self::post(self::$url.'/api/pkcs1/verifySignData',json_encode($c));
        if($res['status']==0){
            $validRes=$res['body']['verifyRes'];
        }
        return $validRes;
    }

    public function post($url, $data_string)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data_string)
        ]);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
        $r = curl_exec($curl);
        curl_close($curl);

        return json_decode($r,true);
    }
}
