• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP openssl_x509_check_private_key函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中openssl_x509_check_private_key函数的典型用法代码示例。如果您正苦于以下问题:PHP openssl_x509_check_private_key函数的具体用法?PHP openssl_x509_check_private_key怎么用?PHP openssl_x509_check_private_key使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了openssl_x509_check_private_key函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。

示例1: validateSslOptions

 protected function validateSslOptions()
 {
     // Get the contents.
     $sslCertFile = file_exists($this->certPath) ? trim(file_get_contents($this->certPath)) : '';
     $sslKeyFile = file_exists($this->keyPath) ? trim(file_get_contents($this->keyPath)) : '';
     $sslChainFiles = $this->assembleChainFiles($this->chainPaths);
     // Do a bit of validation.
     // @todo: Cert first.
     $certResource = openssl_x509_read($sslCertFile);
     if (!$certResource) {
         throw new \Exception("The provided certificate is either not a valid X509 certificate or could not be read.");
     }
     // Then the key. Does it match?
     $keyResource = openssl_pkey_get_private($sslKeyFile);
     if (!$keyResource) {
         throw new \Exception("The provided private key is either not a valid RSA private key or could not be read.");
     }
     $keyMatch = openssl_x509_check_private_key($certResource, $keyResource);
     if (!$keyMatch) {
         throw new \Exception("The provided certificate does not match the provided private key.");
     }
     // Each chain needs to be a valid cert.
     foreach ($sslChainFiles as $chainFile) {
         $chainResource = openssl_x509_read($chainFile);
         if (!$chainResource) {
             throw new \Exception("One of the provided certificates in the chain is not a valid X509 certificate.");
         } else {
             openssl_x509_free($chainResource);
         }
     }
     // Yay we win.
     $this->sslOptions = array('certificate' => $sslCertFile, 'key' => $sslKeyFile, 'chain' => $sslChainFiles);
     return true;
 }
开发者ID:pjcdawkins,项目名称:platformsh-cli,代码行数:34,代码来源:DomainAddCommand.php


示例2: checkPair

 function checkPair($cert, $key, $passphrase = null)
 {
     if (openssl_pkey_get_private($key, $passphrase) === false) {
         return false;
     }
     return openssl_x509_check_private_key($cert, $key);
 }
开发者ID:splitice,项目名称:radical-ssl,代码行数:7,代码来源:X509Helpers.php


示例3: check_privatekey_match_certificate

 function check_privatekey_match_certificate()
 {
     $this->clear_debug_buffer();
     $ok = openssl_x509_check_private_key($this->certificate_resource, $this->privatekey_resource);
     $this->debug("check_privatekey_match_certificate");
     return $ok;
 }
开发者ID:robotamer,项目名称:oldstuff,代码行数:7,代码来源:Openssl.php


示例4: checkSSLKey

 /**
  * Verify if SSL key and certificate match
  * @param $key
  * @param $cert
  * @return bool
  */
 public static function checkSSLKey($key, $cert)
 {
     if (openssl_x509_check_private_key(clean_input($cert), clean_input($key))) {
         return true;
     } else {
         return false;
     }
 }
开发者ID:gOOvER,项目名称:EasySCP,代码行数:14,代码来源:EasySSL.php


示例5: validateSslOptions

 /**
  * @return bool
  */
 protected function validateSslOptions()
 {
     // Get the contents.
     if (!is_readable($this->certPath)) {
         $this->stdErr->writeln("The certificate file could not be read: " . $this->certPath);
         return false;
     }
     $sslCert = trim(file_get_contents($this->certPath));
     // Do a bit of validation.
     $certResource = openssl_x509_read($sslCert);
     if (!$certResource) {
         $this->stdErr->writeln("The certificate file is not a valid X509 certificate: " . $this->certPath);
         return false;
     }
     // Then the key. Does it match?
     if (!is_readable($this->keyPath)) {
         $this->stdErr->writeln("The private key file could not be read: " . $this->keyPath);
         return false;
     }
     $sslPrivateKey = trim(file_get_contents($this->keyPath));
     $keyResource = openssl_pkey_get_private($sslPrivateKey);
     if (!$keyResource) {
         $this->stdErr->writeln("Private key not valid, or passphrase-protected: " . $this->keyPath);
         return false;
     }
     $keyMatch = openssl_x509_check_private_key($certResource, $keyResource);
     if (!$keyMatch) {
         $this->stdErr->writeln("The provided certificate does not match the provided private key.");
         return false;
     }
     // Each chain needs to contain one or more valid certificates.
     $chainFileContents = $this->readChainFiles($this->chainPaths);
     foreach ($chainFileContents as $filePath => $data) {
         $chainResource = openssl_x509_read($data);
         if (!$chainResource) {
             $this->stdErr->writeln("File contains an invalid X509 certificate: " . $filePath);
             return false;
         }
         openssl_x509_free($chainResource);
     }
     // Split up the chain file contents.
     $chain = [];
     $begin = '-----BEGIN CERTIFICATE-----';
     foreach ($chainFileContents as $data) {
         if (substr_count($data, $begin) > 1) {
             foreach (explode($begin, $data) as $cert) {
                 $chain[] = $begin . $cert;
             }
         } else {
             $chain[] = $data;
         }
     }
     // Yay we win.
     $this->sslOptions = ['certificate' => $sslCert, 'key' => $sslPrivateKey, 'chain' => $chain];
     return true;
 }
开发者ID:commerceguys,项目名称:platform-cli,代码行数:59,代码来源:DomainCommandBase.php


示例6: curlContactCert

 public static function curlContactCert($url, $key, $cert, $keypw = false, $postData = null)
 {
     if (is_null($key) || is_null($cert) || $key === "" || $cert === "") {
         throw new ConfusaGenException("Empty key or certificate received " . "when using curlContactCert(). " . "Aborting curl-transfer to url: {$url}");
     }
     if (is_null($postData) || !is_array($postData) || count($postData) == 0) {
         return false;
     }
     /* Do basic URL filtering */
     $curlurl = Input::sanitizeURL($url);
     if (is_null($curlurl) || $curlurl === "" || filter_var($curlurl, FILTER_VALIDATE_URL) === false) {
         Logger::log_event(LOG_NOTICE, "invalid URL (" . $curlurl . "), aborting curl-fetch.");
         return false;
     }
     Logger::log_event(LOG_DEBUG, "Contacting {$curlurl} using cert AuthN");
     /* key should be encrypted, if not, do not use it (not safe!) */
     $start = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
     if (substr($key, 0, strlen($start)) !== $start) {
         Logger::log_event(LOG_NOTICE, "Trying to use curlContactCert with unecrypted private key, aborting.");
         return false;
     }
     $rkey = openssl_pkey_get_private($key, $keypw);
     if ($rkey === false) {
         Logger::log_event(LOG_NOTICE, "Could not parse private key for CurlContactCert, aborting");
         return false;
     }
     if (!openssl_x509_check_private_key($cert, $rkey)) {
         Logger::log_event(LOG_NOTICE, "Provided key and certificate is not a pair, cannot continue.");
         /* throw exception? */
         return false;
     }
     $rcert = new Certificate($cert);
     if (!$rcert->isValid()) {
         $logline = "Certificate (" . $rcert->getHash() . ") has expired, cannot use this. Aborting curl.";
         Logger::log_event(LOG_NOTICE, $logline);
         return false;
     }
     if (!file_exists("/tmp/" . $rcert->getHash() . ".key") || !file_exists("/tmp/" . $rcert->getHash() . ".crt")) {
         if (file_put_contents("/tmp/" . $rcert->getHash() . ".key", $key) === false) {
             Logger::log_event(LOG_NOTICE, "Could not write key to file");
         }
         if (file_put_contents("/tmp/" . $rcert->getHash() . ".crt", $cert) === false) {
             Logger::log_event(LOG_NOTICE, "Could not write cert to file");
         }
     }
     $options = array(CURLOPT_URL => $curlurl, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_SSLKEY => "/tmp/" . $rcert->getHash() . ".key", CURLOPT_SSLCERT => "/tmp/" . $rcert->getHash() . ".crt", CURLOPT_SSLKEYPASSWD => $keypw, CURLOPT_HEADER => false, CURLOPT_FOLLOWLOCATION => true, CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT => 15);
     $channel = curl_init();
     curl_setopt_array($channel, $options);
     $data = curl_exec($channel);
     $status = curl_errno($channel);
     curl_close($channel);
     if ($status !== 0) {
         throw new ConfusaGenException("Could not connect properly to remote " . "endpoint {$curlurl} using cert-based authN! " . "Maybe the Confusa instance is misconfigured? " . "Please contact an administrator!");
     }
     return $data;
 }
开发者ID:henrikau,项目名称:confusa,代码行数:56,代码来源:CurlWrapper.php


示例7: setCertificate

 /**
  * esPaypalButton::setCertificate()
  *
  * @param mixed $certificateFilename - The path to the client certificate
  * @param mixed $privateKeyFilename - The path to the private key corresponding to the certificate
  * @return boolean TRUE if the private key matches the certificate.
  */
 public function setCertificate($certificateFilename, $privateKeyFilename)
 {
     if (is_readable($certificateFilename) && is_readable($privateKeyFilename)) {
         $certificate = openssl_x509_read(file_get_contents($certificateFilename));
         $privateKey = openssl_get_privatekey(file_get_contents($privateKeyFilename));
         if ($certificate !== FALSE && $privateKey !== FALSE && openssl_x509_check_private_key($certificate, $privateKey)) {
             $this->certificate = $certificate;
             $this->certificateFile = $certificateFilename;
             $this->privateKey = $privateKey;
             $this->privateKeyFile = $privateKeyFilename;
             return true;
         }
     }
     return false;
 }
开发者ID:jmiridis,项目名称:atcsf1,代码行数:22,代码来源:esPaypalEncryptor.class.php


示例8: set_certificate

 /**
  * Set our public certificate and private key.
  *
  * @param  string $public_cert
  * @param  string $private_key
  * @return self
  */
 public function set_certificate($public_cert, $private_key)
 {
     // Parse the certificate
     $this->public_cert = openssl_x509_read($public_cert);
     // Parse our private key
     $this->private_key = openssl_get_privatekey($private_key);
     // Validate our certificate & private key
     if (!$this->public_cert || !$this->private_key) {
         throw new SecurityException('Invalid public certificate');
     }
     // Validate that our private key corresponds with our public certificate
     if (!openssl_x509_check_private_key($this->public_cert, $this->private_key)) {
         throw new SecurityException('Your private key does not correspond with your public certificate');
     }
     return $this;
 }
开发者ID:ausbin,项目名称:paypal-tools,代码行数:23,代码来源:EncryptedButton.php


示例9: encrypt

 function encrypt($certificate_id)
 {
     # since this is a shared class, but certs are site-specific, go through include_paths to find realpath
     foreach (explode(':', ini_get('include_path')) as $path) {
         if (file_exists($path . '/paypal/paypal.cert')) {
             $public_file = realpath($path . '/paypal/public.cert');
             $private_file = realpath($path . '/paypal/private.cert');
             $paypal_file = realpath($path . '/paypal/paypal.cert');
             $public_cert = openssl_x509_read(file_get_contents($public_file));
             $private_cert = openssl_get_privatekey(file_get_contents($private_file));
             if (openssl_x509_check_private_key($public_cert, $private_cert) === false) {
                 return false;
             }
             $paypal_cert = openssl_x509_read(file_get_contents($paypal_file));
             break;
         }
     }
     $clear_text = 'cert_id=' . $certificate_id;
     foreach ($this->postvars() as $k => $v) {
         $clear_text .= "\n" . $k . '=' . $v;
     }
     $clear_file = tempnam('/tmp/', 'clear_');
     # alt: sys_get_temp_dir()
     $signed_file = preg_replace('/clear/', 'signed', $clear_file);
     $encrypted_file = preg_replace('/clear/', 'encrypted', $clear_file);
     file_put_contents($clear_file, $clear_text);
     if (!openssl_pkcs7_sign($clear_file, $signed_file, $public_cert, $private_cert, array(), PKCS7_BINARY)) {
         return false;
     }
     list($x, $signed_text) = explode("\n\n", file_get_contents($signed_file));
     #?
     file_put_contents($signed_file, base64_decode($signed_text));
     if (!openssl_pkcs7_encrypt($signed_file, $encrypted_file, $paypal_cert, array(), PKCS7_BINARY)) {
         return false;
     }
     list($x, $encrypted_text) = explode("\n\n", file_get_contents($encrypted_file));
     #?
     $this->encrypted = "\n-----BEGIN PKCS7-----\n{$encrypted_text}\n-----END PKCS7-----\n";
     @unlink($clear_file);
     @unlink($signed_file);
     @unlink($encrypted_file);
 }
开发者ID:songwork,项目名称:songwork,代码行数:42,代码来源:PayPalButton.php


示例10: update_ssl_data

function update_ssl_data()
{
    // Get a reference to the Config object
    $cfg = EasySCP_Registry::get('Config');
    // Gets a reference to the EasySCP_ConfigHandler_Db instance
    $db_cfg = EasySCP_Registry::get('Db_Config');
    $db_cfg->resetQueriesCounter('update');
    $sslkey = clean_input(filter_input(INPUT_POST, 'ssl_key'));
    $sslcert = clean_input(filter_input(INPUT_POST, 'ssl_cert'));
    $sslcacert = clean_input(filter_input(INPUT_POST, 'ssl_cacert'));
    $sslstatus = clean_input(filter_input(INPUT_POST, 'ssl_status'));
    if (openssl_x509_check_private_key($sslcert, $sslkey)) {
        // update the ssl related values
        $db_cfg->SSL_KEY = $sslkey;
        $db_cfg->SSL_CERT = $sslcert;
        $db_cfg->SSL_CACERT = $sslcacert;
        $db_cfg->SSL_STATUS = $sslstatus;
        $cfg->replaceWith($db_cfg);
        /*
        $data = array (
        	'SSL_KEY'	=> $sslkey,
        	'SSL_CERT'	=> $sslcert,
        	'SSL_STATUS'=> $sslstatus
        );
        */
        $data = array('SSL_STATUS' => $sslstatus);
        EasyConfig::Save($data);
        write_log(get_session('user_logged') . ": Updated SSL configuration!");
        // get number of updates
        $update_count = $db_cfg->countQueries('update');
        if ($update_count == 0) {
            set_page_message(tr("SSL configuration unchanged"), 'info');
        } elseif ($update_count > 0) {
            set_page_message(tr('SSL configuration updated!'), 'success');
        }
    } else {
        set_page_message(tr("SSL key/cert don't match"), 'Warning');
        write_log(get_session('user_logged') . ": Update of SSL configuration failed!");
    }
    send_request('110 DOMAIN master');
    user_goto('tools_config_ssl.php');
}
开发者ID:gOOvER,项目名称:EasySCP,代码行数:42,代码来源:tools_config_ssl.php


示例11: setCertificate

 /**
  * Set the client certificate and private key pair.
  *
  * @param string $certificateFilename The path to the client certificate
  * @param string $privateKeyFilename The path to the private key corresponding to the certificate
  * @return bool TRUE if the private key matches the certificate.
  */
 public function setCertificate($certificateFilename, $privateKeyFilename)
 {
     $result = false;
     if (is_readable($certificateFilename) && is_readable($privateKeyFilename)) {
         $certificate = null;
         $handle = fopen($certificateFilename, "r");
         $size = filesize($certificateFilename);
         $certificate = fread($handle, $size);
         fclose($handle);
         $privateKey = null;
         $handle = fopen($privateKeyFilename, "r");
         $size = filesize($privateKeyFilename);
         $privateKey = fread($handle, $size);
         fclose($handle);
         if ($certificate !== false && $privateKey !== false && openssl_x509_check_private_key($certificate, $privateKey)) {
             $this->certificate = $certificate;
             $this->certificateFile = $certificateFilename;
             $this->privateKey = $privateKey;
             $this->privateKeyFile = $privateKeyFilename;
             $result = true;
         }
     }
     return $result;
 }
开发者ID:otoso,项目名称:cakephp-paypal-ipn,代码行数:31,代码来源:PaypalEwp.php


示例12: _encButton

 /**
  *   Create encrypted buttons.
  *
  *   Requires that the plugin is configured to do so, and that the key files
  *   are set up correctly.  If an error is encountered, an empty string
  *   is returned so the caller can proceed with an un-encrypted button.
  *
  *   @since  version 0.4.0
  *   @param  array   $fields     Array of data to encrypt into buttons
  *   @return string              Encrypted_value, or empty string on error
  */
 private function _encButton($fields)
 {
     global $_CONF, $_PP_CONF;
     // Make sure button encryption is enabled and needed values are set
     if ($this->config['encrypt'] != 1 || empty($this->config['prv_key']) || empty($this->config['pub_key']) || empty($this->config['pp_cert']) || $this->cert_id == '') {
         return '';
     }
     // Now check that the files exist and can be read
     foreach (array('prv_key', 'pub_key', 'pp_cert') as $idx => $name) {
         if (!is_file($this->config[$name]) || !is_readable($this->config[$name])) {
             return '';
         }
     }
     // Create a temporary file to begin storing our data.  If this fails,
     // then return.
     $dataFile = tempnam($_PP_CONF['tmpdir'], 'data');
     if (!is_writable($dataFile)) {
         return '';
     }
     $plainText = '';
     $signedText = array();
     $encText = '';
     $pub_key = @openssl_x509_read(file_get_contents($this->config['pub_key']));
     if (!$pub_key) {
         COM_errorLog("Failed reading public key from {$this->config['pub_key']}", 1);
         return '';
     }
     $prv_key = @openssl_get_privatekey(file_get_contents($this->config['prv_key']));
     if (!$prv_key) {
         COM_errorLog("Failed reading private key from {$this->config['prv_key']}", 1);
         return '';
     }
     $pp_cert = @openssl_x509_read(file_get_contents($this->config['pp_cert']));
     if (!$pp_cert) {
         COM_errorLog("Failed reading PayPal certificate from {$this->config['pp_cert']}", 1);
         return '';
     }
     //  Make sure this key and certificate belong together
     if (!openssl_x509_check_private_key($pub_key, $prv_key)) {
         COM_errorLog("Mismatched private & public keys", 1);
         return '';
     }
     //  Start off the form data with the PayPal certificate ID
     $plainText .= "cert_id=" . $this->cert_id;
     //  Create the form data by separating each value set by a new line
     //  Make sure that required fields are available.  We assume that the
     //  item_number, item_name and amount are in.
     if (!isset($fields['business'])) {
         $fields['business'] = $this->receiver_email;
     }
     if (!isset($fields['currency_code'])) {
         $fields['currency_code'] = $this->currency_code;
     }
     foreach ($fields as $key => $value) {
         $plainText .= "\n{$key}={$value}";
     }
     //  First create a file for storing the plain text values
     $fh = fopen($dataFile . '_plain.txt', 'wb');
     if ($fh) {
         fwrite($fh, $plainText);
     } else {
         return '';
     }
     @fclose($fh);
     // Now sign the plaintext values into the signed file
     //$fh = fopen($dataFile . "_signed.txt", "w+");
     if (!openssl_pkcs7_sign($dataFile . '_plain.txt', $dataFile . '_signed.txt', $pub_key, $prv_key, array(), PKCS7_BINARY)) {
         return '';
     }
     //  Parse the signed file between the header and content
     $signedText = explode("\n\n", file_get_contents($dataFile . '_signed.txt'));
     //  Save only the content but base64 decode it first
     $fh = fopen($dataFile . '_signed.txt', 'wb');
     if ($fh) {
         fwrite($fh, base64_decode($signedText[1]));
     } else {
         return '';
     }
     @fclose($fh);
     // Now encrypt the signed file we just wrote
     if (!openssl_pkcs7_encrypt($dataFile . '_signed.txt', $dataFile . '_enc.txt', $pp_cert, array(), PKCS7_BINARY)) {
         return '';
     }
     // Parse the encrypted file between header and content
     $encryptedData = explode("\n\n", file_get_contents($dataFile . "_enc.txt"));
     $encText = $encryptedData[1];
     // Delete all of our temporary files
     @unlink($dataFile);
     @unlink($dataFile . "_plain.txt");
//.........这里部分代码省略.........
开发者ID:JohnToro,项目名称:paypal,代码行数:101,代码来源:paypal.class.php


示例13: actionServerImport


//.........这里部分代码省略.........
     }
     if (count($ca) > 1) {
         $m = 'This certificate cannot be imported because multiple possible ' . 'signers exist.';
         return $m;
     }
     $caId = isset($ca[0]['Id']) ? $ca[0]['Id'] : false;
     if (!is_numeric($caId) or $caId < 1) {
         return 'Failed to locate issuing CA id.';
     }
     // Validate expiration date of CA cert.  Only warn if the expiration dates
     // don't jive.
     $this->ca->resetProperties();
     if ($this->ca->populateFromDb($caId) === false) {
         return 'Failed to locate issuer information.';
     }
     $caValidTo = $this->ca->getProperty('ValidTo');
     if (substr($validTo, 0, 10) > substr($caValidTo, 0, 10)) {
         $m = 'WARNING: The certificate expiration date is invalid, the issuer ' . 'certficate expires ' . $caValidTo . ', this certificate expires ' . $validTo . '.';
         $this->html->errorMsgSet($m);
     }
     // Determine the last serial number issued by the ca in case the
     // serial number of the current certificate is higher and we need
     // to bump the ca last serial issued.
     $caLastSerial = $this->ca->getLastSerialIssued($caId);
     if ($caLastSerial === false or !is_numeric($caLastSerial)) {
         return 'Failed to determine CA last serial issued.';
     }
     // Validate the private key
     if (is_string($privKey)) {
         $pKey = openssl_pkey_get_private($privKey, $passPhrase);
         if ($pKey === false) {
             return 'Private key or password is invalid.';
         }
         if (!openssl_x509_check_private_key($pemCert, $pKey)) {
             return 'Private key does not belong to cert.';
         }
     }
     // Did they include a csr?
     if (is_string($certRequest)) {
         $csrPubKey = openssl_csr_get_public_key($certRequest);
         if ($csrPubKey === false) {
             return 'Failed to extract public key from CSR.';
         }
         if (openssl_pkey_get_details($pubKeyRes) !== openssl_pkey_get_details($csrPubKey)) {
             return 'CSR and cert do not match.';
         }
     }
     // Import the cert into the database
     $this->server->resetProperties();
     // required properties
     $this->server->setProperty('Certificate', $pemCert);
     $this->server->setProperty('CommonName', implode("\n", $pc['certificate']['subject']['CommonName']));
     $this->server->setProperty('CreateDate', 'now()');
     $this->server->setProperty('Description', 'imported');
     $this->server->setProperty('FingerprintMD5', $pc['fingerprints']['md5']);
     $this->server->setProperty('FingerprintSHA1', $pc['fingerprints']['sha1']);
     $this->server->setProperty('ParentId', $caId);
     $this->server->setProperty('PrivateKey', $privKey);
     $this->server->setProperty('PublicKey', $pubKey);
     $this->server->setProperty('SerialNumber', $serialNumber);
     $this->server->setProperty('ValidFrom', $validFrom);
     $this->server->setProperty('ValidTo', $validTo);
     // optional properties
     if (is_string($certRequest)) {
         $this->server->setProperty('CSR', $certRequest);
     }
开发者ID:bizonix,项目名称:phpMyCA,代码行数:67,代码来源:webapp.php


示例14: file_get_contents

  </tr>
  <tr>
    <th scope="row">&nbsp;</th>
    <td>
      <input type="checkbox" name="auto_cert" value="auto_cert" onclick="jQuery('.manual_cert').toggle('300');"/>&nbsp;&nbsp;Generate a new certificate and private key for me<br/>
    </td>
  </tr>
  <tr valign="top" class="manual_cert">
    <th scope="row"><label for="certificate">Signing Certificate</label></th>
    <?php 
if (file_exists(constant('SAMLAUTH_CONF') . '/certs/' . get_current_blog_id() . '/' . get_current_blog_id() . '.cer') && file_exists(constant('SAMLAUTH_CONF') . '/certs/' . get_current_blog_id() . '/' . get_current_blog_id() . '.key')) {
    $certificate = file_get_contents(constant('SAMLAUTH_CONF') . '/certs/' . get_current_blog_id() . '/' . get_current_blog_id() . '.cer');
    $certificate_cn = openssl_x509_parse($certificate);
    $certificate_cn = $certificate_cn['subject']['CN'];
    $privatekey = file_get_contents(constant('SAMLAUTH_CONF') . '/certs/' . get_current_blog_id() . '/' . get_current_blog_id() . '.key');
    $privatekey_match = openssl_x509_check_private_key($certificate, $privatekey);
} else {
    $certificate = false;
    $privatekey = false;
    $privatekey_match = false;
}
?>
    <td><input type="file" name="certificate" id="certificate" /><?php 
if ($certificate !== false) {
    echo '&nbsp;<span class="green">Using certificate: <strong>' . $certificate_cn . '</strong>.</span> <a href="' . constant('SAMLAUTH_CONF_URL') . '/certs/' . get_current_blog_id() . '/' . get_current_blog_id() . '.cer' . '" target="_blank">[download]</a>';
}
?>
    <br/>
    <span class="setting-description">This doesn't have to be the certificate used to secure your website, it can just be self-signed.</span>
    </td>
  </tr>
开发者ID:hooplad,项目名称:saml-20-single-sign-on,代码行数:31,代码来源:sso_sp.php


示例15: check_pair

function check_pair($cert, $priv)
{
    $msg = openssl_x509_check_private_key($cert, $priv) ? '+Ok, Match' : '-Err, Not Match';
    echo $msg . "\n\n";
}
开发者ID:jinguanio,项目名称:david,代码行数:5,代码来源:csr_check.php


示例16: _paypalEncrypt

	/**
	 * Encrypts and signs the request to paypal
	 *
	 * To generate a keypair:
	 * openssl genrsa -des3 -out privkey.pem 2048
	 * openssl req -new -x509 -key privkey.pem -out cacert.pem -days 3650
	 * 
	 * To encrypt and sign (that's what we do here):
	 * openssl smime -sign -signer cacert.pem -inkey privkey.pem -outform der -nodetach -binary -passin pass:1234 | openssl smime -encrypt -des3 -binary -outform pem paypal_cert_pem.txt
	 *
	 * @param  string        $cleartext  Cleartext to encrypt and sign
	 * @return string                    Encrypted text or FALSE
	 */
	private function _paypalEncrypt( $cleartext )
	{
		$return							=	false;

		$paypal_openssl_path			=	$this->params->get( 'openssl_exec_path', '/usr/bin/openssl' );
		$paypal_public_certificate_path	=	$this->getAccountParam( 'paypal_public_certificate_path' );
		$paypal_private_key_path		=	$this->getAccountParam( 'paypal_private_key_path' );
		$paypal_public_key_path			=	$this->getAccountParam( 'paypal_public_key_path' );
		$paypal_private_key_password	=	$this->getAccountParam( 'paypal_private_key_password' );

		$tmpDir							=	$this->findATmpDir();
		if ( ( $tmpDir === null ) || ( ! is_dir( $tmpDir ) ) || ! is_writable( $tmpDir ) ) {
			$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl', 'did not find a writable temporary directory (' . $tmpDir . '). Please make sure that your cachepath global CMS setting is a writable directory.' );
			$tmpDir						=	null;
		}

		$h = @getenv('HOME') . "\n";
		if ( ! is_writable( $h ) ) {
			@putenv("HOME=/tmp");		// try avoiding unable to write 'random state'		( http://www.paypaldeveloper.com/pdn/board/message?board.id=ewp&thread.id=110&view=by_date_ascending&page=2 )
		} else {
			$h			=	null;
		}

		if ( extension_loaded( 'openssl' ) && defined( 'OPENSSL_VERSION_TEXT' ) && ( $tmpDir !== null ) ) {

			$clearFile					=	tempnam($tmpDir, 'clr_');
			$signedFile					=	tempnam($tmpDir, 'sign_');
			$encryptedFile				=	tempnam($tmpDir, 'encr_');

			if ( is_readable( $paypal_public_key_path ) && is_readable( $paypal_private_key_path ) && is_readable( $paypal_public_certificate_path ) ) {
				$certificate			=	openssl_x509_read( file_get_contents( $paypal_public_key_path ) );
				$privateKey				=	openssl_pkey_get_private( file_get_contents( $paypal_private_key_path ), $paypal_private_key_password );
				$paypalcert				=	openssl_x509_read( file_get_contents( $paypal_public_certificate_path ) );
				if ( ( $certificate !== false ) && ( $privateKey !== false ) && ( $paypalcert !== false ) ) {
					$privOk				=	openssl_x509_check_private_key( $certificate, $privateKey );
					if ( $privOk ) {
						$out			=	fopen( $clearFile, 'wb' );
						if ( $out !== false ) {
							fwrite( $out, $cleartext );
							fclose( $out );
	
							if ( openssl_pkcs7_sign( $clearFile, $signedFile, $certificate, $privateKey, array(), PKCS7_BINARY ) ) {
								@unlink( $clearFile );
			
								$signedData		=	explode( "\n\n", file_get_contents( $signedFile ) );
				
								$out			=	fopen($signedFile, 'wb');
								if ( $out !== false ) {
									fwrite( $out, base64_decode( $signedData[1] ) );
									fclose( $out );
				
									if ( openssl_pkcs7_encrypt( $signedFile, $encryptedFile, $paypalcert, array(), PKCS7_BINARY ) ) {
										@unlink( $signedFile );
										$encryptedData	=	explode("\n\n", file_get_contents( $encryptedFile ), 2 );
										@unlink( $encryptedFile );

										$return	=	"-----BEGIN PKCS7-----\n"
												.	trim( $encryptedData[1] )
												.	"\n-----END PKCS7-----";
									} else {
										$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_pkcs7_encrypt(signedFile,paypal_public_cer) ', 'returns an error on signature.' );
									}
								} else {
									$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl open ', $signedFile . ' returns an error creating it.' );
								}
							} else {
								$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_pkcs7_sign(message,your_private_key)', 'returns an error.' );
							}
						} else {
							$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl open ', $clearFile . ' returns an error creating it.' );
						}	
					} else {
						$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_pkcs7_sign(message,your_private_key)', 'returns an error.' );
					}
				} else {
					if ( $certificate === false ) {
						$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_x509_read(your_public_key)', 'returns an error.' );
					}
					if ( $privateKey === false ) {
						$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_pkey_get_private(your_private_key)', 'returns an error. Maybe wrong password for private key ?' );
					}
					if ( $paypalcert === false ) {
						$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_x509_read(paypal_public_certificate)', 'returns an error.' );
					}
				}
			} else {
				$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl tempnam()', 'returns unwritable filepaths (' . $clearFile . ')' );
//.........这里部分代码省略.........
开发者ID:kosmosby,项目名称:medicine-prof,代码行数:101,代码来源:cbpaidsubscriptions.paypal.php


示例17: setCertificate

 /**
  * Set the client certificate and private key pair.
  *
  * @param string $certificateFilename The path to the client
  * (public) certificate
  * @param string $privateKeyFilename The path to the private key
  * corresponding to the certificate
  * @return bool TRUE if the private key matches the certificate,
  * FALSE otherwise
  */
 function setCertificate($certificateFilename, $privateKeyFilename)
 {
     if (is_readable($certificateFilename) and is_readable($privateKeyFilename)) {
         $handle = fopen($certificateFilename, "r");
         if ($handle === false) {
             return false;
         }
         $size = filesize($certificateFilename);
         $certificate = fread($handle, $size);
         @fclose($handle);
         unset($handle);
         $handle = fopen($privateKeyFilename, "r");
         if ($handle === false) {
             return false;
         }
         $size = filesize($privateKeyFilename);
         $privateKey = fread($handle, $size);
         @fclose($handle);
         if ($certificate !== false and $privateKey !== false and openssl_x509_check_private_key($certificate, $privateKey)) {
             $this->certificate = $certificate;
             $this->certificateFile = $certificateFilename;
             $this->privateKey = $privateKey;
             $this->privateKeyFile = $privateKeyFilename;
             return true;
         }
     } else {
         $this->error = 2;
         return false;
     }
 }
开发者ID:NatemcM,项目名称:yab_shop,代码行数:40,代码来源:yab_shop_3rd_party.php


示例18: client_addSslCert

/**
 * Add or update an SSL certificate
 *
 * @throws iMSCP_Exception
 * @throws iMSCP_Exception_Database
 * @param int $domainId domain unique identifier
 * @param string $domainType Domain type (dmn|als|sub|alssub)
 * @return void
 */
function client_addSslCert($domainId, $domainType)
{
    $config = iMSCP_Registry::get('config');
    $domainName = _client_getDomainName($domainId, $domainType);
    $selfSigned = isset($_POST['selfsigned']);
    if ($domainName === false) {
        showBadRequestErrorPage();
    }
    if ($selfSigned && !client_generateSelfSignedCert($domainName)) {
        set_page_message(tr('Could not generate SSL certificate. An unexpected error occurred.'), 'error');
        return;
    }
    if (!isset($_POST['passphrase']) || !isset($_POST['private_key']) || !isset($_POST['certificate']) || !isset($_POST['ca_bundle']) || !isset($_POST['cert_id'])) {
        showBadRequestErrorPage();
    }
    $passPhrase = clean_input($_POST['passphrase']);
    $privateKey = clean_input($_POST['private_key']);
    $certificate = clean_input($_POST['certificate']);
    $caBundle = clean_input($_POST['ca_bundle']);
    $certId = intval($_POST['cert_id']);
    if (!$selfSigned) {
        // Validate SSL certificate (private key, SSL certificate and certificate chain)
        $privateKey = @openssl_pkey_get_private($privateKey, $passPhrase);
        if (!is_resource($privateKey)) {
            set_page_message(tr('Invalid private key or passphrase.'), 'error');
            return;
        }
        $certificateStr = $certificate;
        $certificate = @openssl_x509_read($certificate);
        if (!is_resource($certificate)) {
            set_page_message(tr('Invalid SSL certificate.'), 'error');
            return;
        }
        if (!@openssl_x509_check_private_key($certificate, $privateKey)) {
            set_page_message(tr("The private key doesn't belong to the provided SSL certificate."), 'error');
            return;
        }
        if (!($tmpfname = @tempnam(sys_get_temp_dir(), intval($_SESSION['user_id']) . 'ssl-ca'))) {
            write_log('Could not create temporary file for CA bundle..', E_USER_ERROR);
            set_page_message(tr('Could not add/update SSL certificate. An unexpected error occurred.'), 'error');
            return;
        }
        register_shutdown_function(function ($file) {
            @unlink($file);
        }, $tmpfname);
        if ($caBundle !== '') {
            if (!@file_put_contents($tmpfname, $caBundle)) {
                write_log('Could not export customer CA bundle in temporary file.', E_USER_ERROR);
                set_page_message(tr('Could not add/update SSL certificate. An unexpected error occurred.'), 'error');
                return;
            }
            // Note: Here we also add the CA bundle in the trusted chain to support self-signed certificates
            if (@openssl_x509_checkpurpose($certificate, X509_PURPOSE_SSL_SERVER, array($config['DISTRO_CA_BUNDLE'], $tmpfname), $tmpfname)) {
                set_page_message(tr('At least one intermediate certificate is invalid or missing.'), 'error');
                return;
            }
        } else {
            @file_put_contents($tmpfname, $certificateStr);
            // Note: Here we also add the certificate in the trusted chain to support self-signed certificates
            if (!@openssl_x509_checkpurpose($certificate, X509_PURPOSE_SSL_SERVER, array($config['DISTRO_CA_BUNDLE'], $tmpfname))) {
                set_page_message(tr('At least one intermediate certificate is invalid or missing.'), 'error');
                return;
            }
        }
    }
    // Preparing data for insertion in database
    if (!$selfSigned) {
        if (!@openssl_pkey_export($privateKey, $privateKeyStr)) {
            write_log('Could not export private key.', E_USER_ERROR);
            set_page_message(tr('Could not add/update SSL certificate. An unexpected error occurred.'), 'error');
            return;
        }
        @openssl_pkey_free($privateKey);
        if (!@openssl_x509_export($certificate, $certificateStr)) {
            write_log('Could not export SSL certificate.', E_USER_ERROR);
            set_page_message(tr('Could not add/update SSL certificate. An unexpected error occurred.'), 'error');
            return;
        }
        @openssl_x509_free($certificate);
        $caBundleStr = str_replace("\r\n", "\n", $caBundle);
    } else {
        $privateKeyStr = $privateKey;
        $certificateStr = $certificate;
        $caBundleStr = $caBundle;
    }
    $db = iMSCP_Database::getInstance();
    try {
        $db->beginTransaction();
        if ($certId == 0) {
            // Add new certificate
            exec_query('
//.........这里部分代码省略.........
开发者ID:svenjantzen,项目名称:imscp,代码行数:101,代码来源:cert_view.php


示例19: fopen

<?php

$fp = fopen(dirname(__FILE__) . "/cert.crt", "r");
$a = fread($fp, 8192);
fclose($fp);
$fp = fopen(dirname(__FILE__) . "/private.key", "r");
$b = fread($fp, 8192);
fclose($fp);
$cert = "file://" . dirname(__FILE__) . "/cert.crt";
$key = "file://" . dirname(__FILE__) . "/private.key";
var_dump(openssl_x509_check_private_key($cert, $key));
var_dump(openssl_x509_check_private_key("", $key));
var_dump(openssl_x509_check_private_key($cert, ""));
var_dump(openssl_x509_check_private_key("", ""));
var_dump(openssl_x509_check_private_key($a, $b));
开发者ID:badlamer,项目名称:hhvm,代码行数:15,代码来源:009.php


示例20: idpinstaller_hook_step7

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP openssl_x509_checkpurpose函数代码示例发布时间:2022-05-15
下一篇:
PHP openssl_verify函数代码示例发布时间:2022-05-15
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap