带证书请求

@param $url string 请求的网址
@param $vars 请求的参数
@param $certPemPath string 证书路径
@param $keyPemPath  string 证书路径
@param int $second  int 请求超时时间
@param array $aHeader array 请求头选项
@return mixed
177649
function curlPostWithCert($url, $vars, $certPemPath, $keyPemPath, $second=50,$aHeader=array())
    {
        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLCERT, $certPemPath);  //__DIR__ . '/cert/apiclient_cert.pem'
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLKEY, $keyPemPath); //__DIR__ . '/cert/apiclient_key.pem'

        if( count($aHeader) >= 1 ){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }

        curl_setopt($ch,CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
        $result = curl_exec($ch);
        if($result === false){
            $error = curl_error($ch);
            echo "curl错误信息:$error\n";
        }

        curl_close($ch);
        return $result;
    }
907861
protected function _setSmtpProtocol($url)
    {
        $protocol = '';
        $smtpHost = $url;
        $match = [];
        if (Str::getStr()->preg_match('@^([0-9a-z]+://)?(.*)$@i', $url, $match)) {
            if ($match[1]) {
                if (($match[1] == 'ssl://') || ($match[1] == 'tls://')) {
                    $this->set("SMTPSecure", substr($match[1], 0, 3));
                } else {
                    $protocol = $match[1];
                }
            }
            $smtpHost = $match[2];
        }

        return $protocol . $smtpHost;
    }
1234785
public static String getTransferInfo(Map<String, String> params, String certPath, String certPassword) {
		return WxPayApi.doPostSSL(GETTRANSFERINFO_URL, params, certPath, certPassword);
	}
741420
public function multi_layer_route($url, $namespace, $default_controler) {
        list($classname, $funcname, $args, $nouse) = self::multi_layer_info($url);
        $classname = str_replace('/', '\\', $classname);
        if ($classname == '') {
            $classname = '\\' . $default_controler;
        }
        if ($classname == '') {
            throw new Exception('未指定Controler.');
        }
        $classname = $namespace . ucwords($classname, '\\');
        if (!class_exists($classname)) {
            throw new Exception('Controler ' . $classname . '不存在.');
        }
        $controler = new $classname();
        if (!$controler instanceof Controler) {
            throw new Exception($classname . '不是一个Controler对象.');
        }
        $controler->dispatch($funcname, $args);
        return;
    }
608994
private function matchKeyValue(string $path, array $methods)
    {
        foreach ($methods as $method) {
            $keyValue = $this->keyValueRoutes[$method][$path] ?? null;
            if (!\is_null($keyValue)) {
                list($handler, $extraParams) = $keyValue;

                return new InternalRoute($handler, $extraParams);
            }
        }

        return null;
    }
880648
public List<Certificate> getUrlCerts(URL url) {

        SSLSocket socket = null;

        TrustManager trm = new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        };

        try {

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{trm}, null);
            SSLSocketFactory factory = sc.getSocketFactory();
            socket = (SSLSocket) factory.createSocket(url.getHost(), (url.getPort() == -1) ? url.getDefaultPort() : url.getPort());
            socket.startHandshake();
            SSLSession session = socket.getSession();
            Certificate[] certArray = session.getPeerCertificates();
            return new ArrayList<Certificate>(Arrays.asList(certArray));

        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if (socket != null && socket.isConnected()) {
                try {
                    socket.close();
                } catch (IOException ignored) {}
            }
        }

        return new ArrayList<Certificate>();
    }
167655
public static function createAppCSR($keyPair, $dn) {
    $privKey = new \Crypt_RSA();
    $privKey->loadKey($keyPair['privatekey']);

    $pubKey = new \Crypt_RSA();
    $pubKey->loadKey($keyPair['publickey']);
    $pubKey->setPublicKey();

    $x509 = new \File_X509();
    $x509->setPrivateKey($privKey);
    $x509->setDN($dn);

    $x509->loadCSR($x509->saveCSR($x509->signCSR(Constants::CERT_SIGNATURE_ALGORITHM)));
    $x509->setExtension('id-ce-keyUsage', array('keyEncipherment'));

    $csrData = $x509->signCSR(Constants::CERT_SIGNATURE_ALGORITHM);
    return $x509->saveCSR($csrData);
  }
701876
public function request($url, array $hosts, $otp, $nonce)
    {
        $client = new \Yubikey\Client();
        $pool = new \Yubikey\RequestCollection();

        // Make the requests for the host(s)
        $prefix = ($this->getUseSecure() === true) ? 'https' : 'http';
        foreach ($hosts as $host) {
            $link = $prefix.'://'.$host.$url;
            $pool->add(new \Yubikey\Request($link));
        }
        $responses = $client->send($pool);
        $responseCount = count($responses);

        for ($i = 0; $i < $responseCount; $i++) {
            $responses[$i]->setInputOtp($otp)->setInputNonce($nonce);

            if ($this->validateResponseSignature($responses[$i]) === false) {
                unset($responses[$i]);
            }
        }

        return $responses;
    }
393740
public static function createCrlDistCSR($keyPair, $dn) {
    $privKey = new \Crypt_RSA();
    $privKey->loadKey($keyPair['privatekey']);

    $pubKey = new \Crypt_RSA();
    $pubKey->loadKey($keyPair['publickey']);
    $pubKey->setPublicKey();

    $csr = new \File_X509();
    $csr->setPrivateKey($privKey);
    $csr->setPublicKey($pubKey);
    $csr->setDN($dn);
    $csr->loadCSR($csr->saveCSR($csr->signCSR(Constants::CERT_SIGNATURE_ALGORITHM)));
    $csr->setExtension('id-ce-keyUsage', array('cRLSign'));

    $csrData = $csr->signCSR(Constants::CERT_SIGNATURE_ALGORITHM);
    return $csr->saveCSR($csrData);
  }
222205
protected static String postSSL(String url, String data, String certPath, String certPass) {
		HttpsURLConnection conn = null;
		OutputStream out = null;
		InputStream inputStream = null;
		BufferedReader reader = null;
		try {
			KeyStore clientStore = KeyStore.getInstance("PKCS12");
			clientStore.load(new FileInputStream(certPath), certPass.toCharArray());
			KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			kmf.init(clientStore, certPass.toCharArray());
			KeyManager[] kms = kmf.getKeyManagers();
			SSLContext sslContext = SSLContext.getInstance("TLSv1");

			sslContext.init(kms, null, new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
			URL _url = new URL(url);
			conn = (HttpsURLConnection) _url.openConnection();

			conn.setConnectTimeout(25000);
			conn.setReadTimeout(25000);
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);

			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty("User-Agent", DEFAULT_USER_AGENT);
			conn.connect();

			out = conn.getOutputStream();
			out.write(data.getBytes(Charsets.UTF_8));
			out.flush();

			inputStream = conn.getInputStream();
			reader = new BufferedReader(new InputStreamReader(inputStream, Charsets.UTF_8));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line).append("\n");
			}
			return sb.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			IOUtils.closeQuietly(out);
			IOUtils.closeQuietly(reader);
			IOUtils.closeQuietly(inputStream);
			if (conn != null) {
				conn.disconnect();
			}
		}
	}
720408
public static String getCertIdByKeyStoreMap(String certPath, String certPwd) {
		if (!keyStoreMap.containsKey(certPath)) {
			// 缓存中未查询到,则加载RSA证书
			loadSignCert(certPath, certPwd);
		}
		return getCertIdIdByStore(keyStoreMap.get(certPath));
	}
491801
public static function getCNPJCert($certPem)
    {
        $certDer = self::pem2Der((string) $certPem);
        $data = self::getOIDdata((string) $certDer, '2.16.76.1.3.3');

        return (string) $data[0][1][1][0][1];
    }
1089010
public function clientSideCert($cert, $key, $passphrase = null, $encoding = 'PEM')
    {
        $this->client_cert          = $cert;
        $this->client_key           = $key;
        $this->client_passphrase    = $passphrase;
        $this->client_encoding      = $encoding;

        return $this;
    }
522805
public function loadFromUrl(string $url, array $header = []): JWKSet
    {
        $content = $this->getContent($url, $header);
        $data = $this->jsonConverter->decode($content);
        if (!\is_array($data)) {
            throw new \RuntimeException('Invalid content.');
        }

        $keys = [];
        foreach ($data as $kid => $cert) {
            if (false === \mb_strpos($cert, '-----BEGIN CERTIFICATE-----')) {
                $cert = '-----BEGIN CERTIFICATE-----'.PHP_EOL.$cert.PHP_EOL.'-----END CERTIFICATE-----';
            }
            $jwk = KeyConverter::loadKeyFromCertificate($cert);
            if (\is_string($kid)) {
                $jwk['kid'] = $kid;
                $keys[$kid] = JWK::create($jwk);
            } else {
                $keys[] = JWK::create($jwk);
            }
        }

        return JWKSet::createFromKeys($keys);
    }
694415
public static PrivateKey getSignCertPrivateKeyByStoreMap(String certPath,
			String certPwd) {
		if (!keyStoreMap.containsKey(certPath)) {
			loadSignCert(certPath, certPwd);
		}
		try {
			Enumeration<String> aliasenum = keyStoreMap.get(certPath)
					.aliases();
			String keyAlias = null;
			if (aliasenum.hasMoreElements()) {
				keyAlias = aliasenum.nextElement();
			}
			PrivateKey privateKey = (PrivateKey) keyStoreMap.get(certPath)
					.getKey(keyAlias, certPwd.toCharArray());
			return privateKey;
		} catch (KeyStoreException e) {
			LogUtil.writeErrorLog("getSignCertPrivateKeyByStoreMap Error", e);
			return null;
		} catch (UnrecoverableKeyException e) {
			LogUtil.writeErrorLog("getSignCertPrivateKeyByStoreMap Error", e);
			return null;
		} catch (NoSuchAlgorithmException e) {
			LogUtil.writeErrorLog("getSignCertPrivateKeyByStoreMap Error", e);
			return null;
		}
	}
116632
public static function request($url, $param_keys, $ssl = false, $recheck = true)
    {
        $params         = array_filter(Datasheet::get($param_keys));
        $params['sign'] = self::signature($params, Datasheet::get('md5_key'));

        $client = new Client();
        $option = ['body' => Xml::arrToXml($params)];

        if ($ssl === true) {
            $option['cert']    = Datasheet::get('pem_cert');
            $option['ssl_key'] = Datasheet::get('pem_key');
        }

        $response = $client->request('POST', $url, $option);

        if ($response->getStatusCode() != '200') {
            throw new \Exception('网络发生错误，请稍后再试。cURL返回码：' . $response->getReasonPhrase());
        }
        $xml = $response->getBody()->getContents();

        return self::response(Xml::xmlToArr($xml), Datasheet::get('md5_key'), $recheck);
    }
500799
private function getRequestHeaders($url, array $parameters)
    {
        $headers = array();

        if (isset($this->clientId) && isset($this->sharedSecret)) {
            $objectIdentifier = null;
            if ($this->apiVersion === '1.1' && isset($parameters['id'])) {
                $objectIdentifier = $parameters['id'];
            } elseif ($this->apiVersion === '1.0' && isset($parameters['api_id'])) {
                $objectIdentifier = $parameters['api_id'];
            }

            $headers['X-Tulip-Client-ID'] = $this->clientId;
            $headers['X-Tulip-Client-Authentication'] = hash_hmac('sha256', $this->clientId.$url.$objectIdentifier, $this->sharedSecret);
        }

        return $headers;
    }