<?php
/**
* LINE相关
*/
class ModelVerifyhw
{
    protected $_publicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoLnQerStmIxnvoXytYKHCKiGDBG8LDjt4fRWbXkr9Na3V2j6rIs42pN/ItiFfA2zNlUnbsCGDcQ/JYEtbBasAR92RDwEwwkckdGdzIiNzmQpB2uTh6Q+wlHCh+vFfnoRkIDdLr97lemZGEmJea8yW3W9aymNPBMDCDvhV/CO/tGuJZ4xLIA0yLd5T73WoqaTlt0HoJZdNnixhbuC8a/gnEvPUM6A9ZxZIfl+7A6EpuHBq3vUvH1SgMQatC7BCKSUiqZDdgnjj/PX7i4OJFC3klQek2DVQoVBfyyPdUTSlY8hT+RqUN1xD9t+jllEjeAkVqf+VsgycgguS1Sj4PhNiwIDAQAB';

    /**
     * 验证该用户信息的合法性
     * @param $data
     * @return string
     */
	public function validateHW($data)
    {
        if(empty($data)) {
            return [];
        }

        $signature = $data['signature'];
        unset($data['signature']);
        $urlParam = $this->dealUrlParam($data);
        $cpSign = $this->verify($urlParam, $signature);
        if(!empty($cpSign)) {
            oo::logs()->debug3('cpsign:'.$cpSign.'  urlParam:'.$urlParam, 'hwVerifyFail.php');
            return [];
        }
        return $data;
    }


    /**
     * 对参数进行处理
     * @param $data
     * @return string
     */
    private function dealUrlParam($data)
    {
        $urlParam = '';
        //按ascii码升序排列
        ksort($data);
        foreach ($data as $key => $v) {
            if(empty($v)) {
                continue;
            }
//            $v = urldecode($v);
            $urlParam .= '&'.$key .'='.$v;
        }
        $urlParam = ltrim($urlParam, '&');
        return $urlParam;
    }

    /**
     * 使用RSA算法  SHA1WithRSA进行签名  --取消（SHA256WithRSA）
     * @param $data
     * @return string
     */
	protected function verify($data, $signature)
    {
        $key = "-----BEGIN PUBLIC KEY-----\n".chunk_split( $this->_publicKey, 64, "\n" ).'-----END PUBLIC KEY-----';
        $key = openssl_get_publickey( $key );

        if ( empty( $key ) )
        {
            return 'Please pass a Base64-encoded public key from the Market portal';
        }
        $signature = str_replace('\\', '', $signature);
        $signature = str_replace(' ', '+', $signature);
        $result = openssl_verify( $data, base64_decode( $signature ), $key, OPENSSL_ALGO_SHA1 );

        if ( 0 === $result )
        {
            oo::logs()->debug3('openssl error string:'.openssl_error_string()."\n".' 验签的参数:'.$data."\n".'  验签的signature:'.$signature, 'hw_verify.php');
            return 'fail to verify';
        }
        else if ( 1 !== $result )
        {
            return 'Unknown error verifying the signature in openssl_verify '.$result;
        }

        return '';
    }




}