public function field_private_certificate($field) { $certificate = get_post_meta(get_the_ID(), '_pronamic_gateway_ideal_private_certificate', true); if (!empty($certificate)) { $fingerprint = Pronamic_WP_Pay_Gateways_IDealAdvanced_Security::getShaFingerprint($certificate); $fingerprint = str_split($fingerprint, 2); $fingerprint = implode(':', $fingerprint); echo '<dl>'; echo '<dt>', esc_html__('SHA Fingerprint', 'pronamic_ideal'), '</dt>'; echo '<dd>', esc_html($fingerprint), '</dd>'; $info = openssl_x509_parse($certificate); if ($info) { $date_format = __('M j, Y @ G:i', 'pronamic_ideal'); if (isset($info['validFrom_time_t'])) { echo '<dt>', esc_html__('Valid From', 'pronamic_ideal'), '</dt>'; echo '<dd>', esc_html(date_i18n($date_format, $info['validFrom_time_t'])), '</dd>'; } if (isset($info['validTo_time_t'])) { echo '<dt>', esc_html__('Valid To', 'pronamic_ideal'), '</dt>'; echo '<dd>', esc_html(date_i18n($date_format, $info['validTo_time_t'])), '</dd>'; } } echo '</dl>'; } echo '<div>'; submit_button(__('Download Private Certificate', 'pronamic_ideal'), 'secondary', 'download_private_certificate', false); echo ' '; echo '<input type="file" name="_pronamic_gateway_ideal_private_certificate_file" />'; echo '</div>'; }
public function __construct($certificate, $dontSkip = FALSE) { $config = Tinebase_Config::getInstance()->get('modssl'); if (is_object($config)) { $this->casfile = $config->casfile; $this->crlspath = $config->crlspath; } $this->status = array('isValid' => true, 'errors' => array()); $this->certificate = self::_fixPemCertificate($certificate); $c = openssl_x509_parse($this->certificate); // define certificate properties $this->serialNumber = $c['serialNumber']; $this->version = $c['version']; $this->subject = $c['subject']; $this->cn = $c['subject']['CN']; $this->issuer = $c['issuer']; $this->issuerCn = $c['issuer']['CN']; $this->hash = $this->_calcHash(); // $dateTimezone = new DateTimeZone(Tinebase_Core::getUserTimezone()); // $locale = new Zend_Locale($_translation->getAdapter()->getLocale()); // Date valid from $this->validFrom = Tinebase_Translation::dateToStringInTzAndLocaleFormat(new Tinebase_DateTime($c['validFrom_time_t'])); // Date valid to $this->validTo = Tinebase_Translation::dateToStringInTzAndLocaleFormat(new Tinebase_DateTime($c['validTo_time_t'])); $this->_parsePurpose($c['purposes']); $this->_parseExtensions($c['extensions']); if (strtolower($this->casfile) != 'skip') { $this->_validityCheck(); // skip validation, we trust the server's result } if (strtolower($this->crlspath) != 'skip' | $dontSkip) { $this->_testRevoked(); // skip test, } }
function EncryptedPin($sPin, $sCardNo, $sPubKeyURL) { global $log; $sPubKeyURL = trim(SDK_ENCRYPT_CERT_PATH, " "); /** * [WeEngine System] Copyright (c) 2014 WE7.CC * WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details. */ $fp = fopen($sPubKeyURL, "r"); if ($fp != NULL) { $sCrt = fread($fp, 8192); fclose($fp); } $sPubCrt = openssl_x509_read($sCrt); if ($sPubCrt === FALSE) { print "openssl_x509_read in false!"; return -1; } $sPubKey = openssl_x509_parse($sPubCrt); $sInput = Pin2PinBlockWithCardNO($sPin, $sCardNo); if ($sInput == 1) { print "Pin2PinBlockWithCardNO Error ! : " . $sInput; return 1; } $iRet = openssl_public_encrypt($sInput, $sOutData, $sCrt, OPENSSL_PKCS1_PADDING); if ($iRet === TRUE) { $sBase64EncodeOutData = base64_encode($sOutData); return $sBase64EncodeOutData; } else { print "openssl_public_encrypt Error !"; return -1; } }
function EncryptedPin($sPin, $sCardNo, $sPubKeyURL) { global $log; $sPubKeyURL = trim(SDK_ENCRYPT_CERT_PATH, " "); $fp = fopen($sPubKeyURL, "r"); if ($fp != NULL) { $sCrt = fread($fp, 8192); fclose($fp); } $sPubCrt = openssl_x509_read($sCrt); if ($sPubCrt === FALSE) { print "openssl_x509_read in false!"; return -1; } $sPubKey = openssl_x509_parse($sPubCrt); $sInput = Pin2PinBlockWithCardNO($sPin, $sCardNo); if ($sInput == 1) { print "Pin2PinBlockWithCardNO Error ! : " . $sInput; return 1; } $iRet = openssl_public_encrypt($sInput, $sOutData, $sCrt, OPENSSL_PKCS1_PADDING); if ($iRet === TRUE) { $sBase64EncodeOutData = base64_encode($sOutData); return $sBase64EncodeOutData; } else { print "openssl_public_encrypt Error !"; return -1; } }
/** * Get signature data from a single signature container. * * @param string $signature * @return array * @throws SetaPDF_Signer_Asn1_Exception */ private static function _getSignatureData($signature) { $data = array('certificates' => array(), 'signerCertificate' => null, 'subject' => null, 'MIDSN' => null); $asn1 = SetaPDF_Signer_Asn1_Element::parse($signature); $certificates = SetaPDF_Signer_Asn1_Element::findByPath('1/0/3', $asn1); $certificates = $certificates->getChildren(); $lastValidToTime = PHP_INT_MAX; for ($no = 0; $no < count($certificates); $no++) { $certificate = $certificates[$no]; $certificate = $certificate->__toString(); $certificate = "-----BEGIN CERTIFICATE-----\n" . chunk_split(base64_encode($certificate)) . "-----END CERTIFICATE-----"; $certificateInfo = openssl_x509_parse($certificate); $data['certificates'][] = $certificateInfo; if (isset($certificateInfo['validTo_time_t']) && $certificateInfo['validTo_time_t'] <= $lastValidToTime) { $lastValidToTime = $certificateInfo['validTo_time_t']; $data['signerCertificate'] = $certificateInfo; } } $data['subject'] = $data['signerCertificate']['name']; // extract MIDSN if (isset($data['signerCertificate']['extensions']['subjectAltName'])) { $subjectAltName = $data['signerCertificate']['extensions']['subjectAltName']; // Format: 'DirName: serialNumber = ID-16981fa2-8998-4125-9a93-5fecbff74515, name = "+41798...", description = test.ch: Signer le document?, pseudonym = MIDCHEGU8GSH6K83' if (preg_match("/pseudonym = ([^,]*)/", $subjectAltName, $match)) { $data['MIDSN'] = $match[1]; } } return $data; }
protected function __construct($developerCert) { $this->setSchema($this->getSchema()); $ocsprequest = $this->OCSPRequest->tbsRequest->requestListSeq->reqCert; $ocsprequest->hashAlgorithm->algorithm = '1.3.14.3.2.26'; // SHA-1 $ocsprequest->hashAlgorithm->parameters = null; if (!file_exists($developerCert)) { throw new Exception('Developer certificate ' . $developerCert . ' does not exist'); } $info = openssl_x509_parse(file_get_contents($developerCert)); if (!isset($info['serialNumber']) || !isset($info['issuer']) || !isset($info['issuer']['OU'])) { throw new Exception('Cannot process developer Certificate ' . $developerCert . ', missing key fields'); } if ($info['issuer']['OU'] != 'http://www.cacert.org') { // other issuers are picky about who they allow to verify, // so we only accept certs from cacert throw new Exception('Cannot verify certificate, ' . 'it is not from cacert.org'); } $ocsprequest->issuerNameHash = pack('C*', '8ba4c9cb172919453ebb8e730991b925f2832265'); $ocsprequest->issuerKeyHash = pack('C*', '16b5321bd4c7f3e0e68ef3bdd2b03aeeb23918d1'); $ocsprequest->serialNumber = $info['serialNumber']; $this->requestExtensions->Inner->Extension->extnID = '1.3.6.1.5.5.7.48.1.2'; // OCSP nonce $this->requestExtensions->Inner->Extension->extnValue = md5($info['serialNumber'] . time(), true); echo $this; }
protected static function getCertIdByCerPath($certPath) { $x509data = file_get_contents($certPath); openssl_x509_read($x509data); $certData = openssl_x509_parse($x509data); return $certData['serialNumber']; }
function verify_certificate_hostname($raw_cert, $host) { $cert_data = openssl_x509_parse($raw_cert); if ($cert_data['subject']['CN']) { $cert_host_names = []; $cert_host_names[] = $cert_data['subject']['CN']; if ($cert_data['extensions']['subjectAltName']) { foreach (explode("DNS:", $cert_data['extensions']['subjectAltName']) as $altName) { foreach (explode(",", $altName) as $key => $value) { if (!empty(str_replace(',', "", "{$value}"))) { $cert_host_names[] = str_replace(" ", "", str_replace(',', "", "{$value}")); } } } } foreach ($cert_host_names as $key => $hostname) { if (strpos($hostname, "*.") === 0) { // wildcard hostname from cert if (explode(".", $host, 2)[1] == explode(".", $hostname, 2)[1]) { // split cert name and host name on . and compare everything after the first dot return true; } } // no wildcard, just regular match if ($host == $hostname) { return true; } } // no match return false; } }
/** * This function returns false if the used auth method cannot be * done without user action (ie fill login/password in the form...). * If it can be done automatically (SSL, CAS, etc...), then try to * authenticate the user, and return true if it succeeds, false * otherwise). * * @returns the username if the authentification succeeds, false if it fails * or is not applicable. * @todo Error handling !!! * @todo return something better than "Unknown user" !!! */ function autoAuth() { include "config.php"; // $certAttributeToDisplay if (isset($_SERVER['SSL_CLIENT_VERIFY']) && $_SERVER['SSL_CLIENT_VERIFY'] == "SUCCESS") { $cert = openssl_x509_parse($_SERVER['SSL_CLIENT_CERT']); if ($cert) { $dn_cert = $cert["name"]; $pattern = "/{$certAttributeToDisplay}=([^\\/=]+)/"; preg_match($pattern, $dn_cert, $matches); // Debug /*echo "<p>You are : $matches[1]</p>\n"; print "certificate: ".$dn_cert."<br />\n"; echo "<p>pattern=$pattern</p>\n"; print_r($matches); echo "<pre>\n"; var_dump($cert); echo "</pre>\n"; */ } // Return the name to display ! return !empty($matches[1]) ? $matches[1] : "Unknown user"; } else { echo "<p>No certificate received from the web server</p>\n"; return false; } }
/** * Parse the certificate. * * @param Certificate $certificate * * @return ParsedCertificate */ public function parse(Certificate $certificate) { $rawData = openssl_x509_parse($certificate->getPEM()); if (!is_array($rawData)) { throw new CertificateParsingException(sprintf('Fail to parse certificate with error: %s', openssl_error_string())); } if (!isset($rawData['subject']['CN'])) { throw new CertificateParsingException('Missing expected key "subject.cn" in certificate'); } if (!isset($rawData['issuer']['CN'])) { throw new CertificateParsingException('Missing expected key "issuer.cn" in certificate'); } if (!isset($rawData['serialNumber'])) { throw new CertificateParsingException('Missing expected key "serialNumber" in certificate'); } if (!isset($rawData['validFrom_time_t'])) { throw new CertificateParsingException('Missing expected key "validFrom_time_t" in certificate'); } if (!isset($rawData['validTo_time_t'])) { throw new CertificateParsingException('Missing expected key "validTo_time_t" in certificate'); } $subjectAlternativeName = []; if (isset($rawData['extensions']['subjectAltName'])) { $subjectAlternativeName = array_map(function ($item) { return explode(':', trim($item), 2)[1]; }, array_filter(explode(',', $rawData['extensions']['subjectAltName']), function ($item) { return false !== strpos($item, ':'); })); } return new ParsedCertificate($certificate, $rawData['subject']['CN'], $rawData['issuer']['CN'], $rawData['subject'] === $rawData['issuer'], new \DateTime('@' . $rawData['validFrom_time_t']), new \DateTime('@' . $rawData['validTo_time_t']), $rawData['serialNumber'], $subjectAlternativeName); }
function webid_claim() { $r = array('uri' => array()); if (isset($_SERVER['SSL_CLIENT_CERT'])) { $pem = $_SERVER['SSL_CLIENT_CERT']; if ($pem) { $x509 = openssl_x509_read($pem); $pubKey = openssl_pkey_get_public($x509); $keyData = openssl_pkey_get_details($pubKey); if (isset($keyData['rsa'])) { if (isset($keyData['rsa']['n'])) { $r['m'] = strtolower(array_pop(unpack("H*", $keyData['rsa']['n']))); } if (isset($keyData['rsa']['e'])) { $r['e'] = hexdec(array_shift(unpack("H*", $keyData['rsa']['e']))); } } $d = openssl_x509_parse($x509); if (isset($d['extensions']) && isset($d['extensions']['subjectAltName'])) { foreach (explode(', ', $d['extensions']['subjectAltName']) as $elt) { if (substr($elt, 0, 4) == 'URI:') { $r['uri'][] = substr($elt, 4); } } } } } return $r; }
/** * @return array x509 certificate. Result of "openssl_x509_parse()" */ public function getCertData() { if (!$this->certData) { $this->certData = openssl_x509_parse($this->raw_cert['cert']); } return $this->certData; }
public function make_request() { $g = stream_context_create(array("ssl" => array("capture_peer_cert" => true))); set_error_handler(function () { return true; }); $r = stream_socket_client("ssl://{$this->target}:{$this->target_port}", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $g); restore_error_handler(); if (!$r) { return true; } else { $cont = stream_context_get_params($r); $cert = openssl_x509_read($cont["options"]["ssl"]["peer_certificate"]); $cert_data = openssl_x509_parse($cert); openssl_x509_export($cert, $out, FALSE); $signature_algorithm = null; if (preg_match('/^\\s+Signature Algorithm:\\s*(.*)\\s*$/m', $out, $match)) { $signature_algorithm = $match[1]; } $this->sha_type = $signature_algorithm; $this->common_name = $cert_data['subject']['CN']; $this->alternative_names = $cert_data['extensions']['subjectAltName']; $this->issuer = $cert_data['issuer']['O']; $this->valid_from = date('m-d-Y H:i:s', strval($cert_data['validFrom_time_t'])); $this->valid_to = date('m-d-Y H:i:s', strval($cert_data['validTo_time_t'])); $this->parse_alternative_names(); } }
/** * Process an authentication response. * * This function saves the state, and if necessary redirects the user to the page where the user * is informed about the expiry date of his/her certificate. * * @param array $state The state of the response. */ public function process(&$state) { assert('is_array($state)'); if (isset($state['isPassive']) && $state['isPassive'] === TRUE) { // We have a passive request. Skip the warning return; } if (!isset($_SERVER['SSL_CLIENT_CERT']) || $_SERVER['SSL_CLIENT_CERT'] == '') { return; } $client_cert = $_SERVER['SSL_CLIENT_CERT']; $client_cert_data = openssl_x509_parse($client_cert); if ($client_cert_data == FALSE) { SimpleSAML\Logger::error('authX509: invalid cert'); return; } $validTo = $client_cert_data['validTo_time_t']; $now = time(); $daysleft = (int) (($validTo - $now) / (24 * 60 * 60)); if ($daysleft > $this->warndaysbefore) { // We have a certificate that will be valid for some time. Skip the warning return; } SimpleSAML\Logger::warning('authX509: user certificate expires in ' . $daysleft . ' days'); $state['daysleft'] = $daysleft; $state['renewurl'] = $this->renewurl; /* Save state and redirect. */ $id = SimpleSAML_Auth_State::saveState($state, 'warning:expire'); $url = SimpleSAML\Module::getModuleURL('authX509/expirywarning.php'); \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); }
public function __construct($pemData) { $this->_pemData = $pemData; $this->_parsed = openssl_x509_parse($pemData); if ($this->_parsed === false) { throw new sspmod_janus_OpenSsl_Certificate_Exception_NotAValidPem("Data '{$pemData}' is not a valid X.509 PEM certificate"); } }
private static function parsePemCert($pemCert) { $parsedCert = openssl_x509_parse($pemCert); if (false === $parsedCert) { throw new InvalidArgumentException('OpenSSL was unable to parse the certificate'); } return $parsedCert; }
public static function checkCertificateCN(\PHPUnit_Framework_TestCase $test, $use, $cn, KeyDescriptor $kd = null) { $test->assertNotNull($kd); $test->assertEquals($use, $kd->getUse()); $test->assertNotEmpty($kd->getCertificate()->getData()); $crt = openssl_x509_parse($kd->getCertificate()->toPem()); $test->assertEquals($cn, $crt['subject']['CN']); }
private function getCertifacateInformation($host) { $sslOptions = stream_context_create(array('ssl' => array('capture_peer_cert' => true))); $request = stream_socket_client('ssl://' . $host . ':443', $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $sslOptions); $content = stream_context_get_params($request); $certinfo = openssl_x509_parse($content['options']['ssl']['peer_certificate']); return $certinfo; }
public function getCertificateInfo($shortnames = true) { if (!$this->certstr) { $this->certstr = file_get_contents($this->certfile); } $info = openssl_x509_parse($this->certstr, $shortnames); return $info; }
/** * Get certificate info. * * @param string $certificate * * @return OpensslCertificate * @throws \InvalidArgumentException */ public function getInfo($certificate) { $result = openssl_x509_parse($certificate); if (!is_array($result)) { throw new \InvalidArgumentException('Could not parse certificate.'); } return new OpensslCertificate($result); }
public function __construct($path, $pass, $demo = false) { if ($demo == true) { $this->url = "https://cistest.apis-it.hr:8449/FiskalizacijaServiceTest"; } $this->setCertificate($path, $pass); $this->privateKeyResource = openssl_pkey_get_private($this->certificate['pkey'], $pass); $this->publicCertificateData = openssl_x509_parse($this->certificate['cert']); }
public function __construct($pemData) { $this->_pemData = $pemData; /** @todo added shutup operator to prevent warning from being thrown, see also: https://bugs.php.net/bug.php?id=66636 _parsed */ $this->_parsed = @openssl_x509_parse($pemData); if ($this->_parsed === false) { throw new Janus_OpenSsl_Certificate_Exception_NotAValidPem("Data '{$pemData}' is not a valid X.509 PEM certificate"); } }
function cert_subject($raw_cert_data) { $cert_data = openssl_x509_parse($raw_cert_data); if (!empty($cert_data['name'])) { return $cert_data['name']; } else { return false; } }
/** * Extract the subject field from the certificate and return the contents * * @throws OffAmazonPaymentsNotifications_InvalidCertificateException if not found * * @return array of contents of the subject if found */ public function getSubject() { $certInfo = openssl_x509_parse($this->_certificate, true); $certSubject = $certInfo["subject"]; if (is_null($certSubject)) { throw new OffAmazonPaymentsNotifications_InvalidCertificateException("Error with certificate - subject cannot be found"); } return $certSubject; }
function get_CN($context) { $ary = stream_context_get_options($context); assert($ary); $cert = $ary['ssl']['peer_certificate']; assert($cert); $cert_ary = openssl_x509_parse($cert); return $cert_ary['subject']['CN']; }
/** * Constructor * * @param array _info information from openssl_x509_parse() or NULL to trigger auto-parsing * @param resource _res resource handle of x.509 certificate */ public function __construct($_info, $_res) { $this->_info = $_info; $this->_res = $_res; if (null === $_info) { if (!is_array($this->_info = openssl_x509_parse($_res, true))) { throw new CertificateException('Cannot parse certificate information', OpenSslUtil::getErrors()); } } }
/** * {@inheritdoc} */ public function parse($content) { $rawData = openssl_x509_parse($content); if (!$rawData) { throw new ParsingCertificateException(sprintf('Certificate parsing failed with error: %s', openssl_error_string())); } return new CertificateMetadata($rawData['subject']['CN'], $rawData['issuer']['CN'], false !== strpos($rawData['extensions']['authorityKeyIdentifier'], $rawData['extensions']['subjectKeyIdentifier']), $rawData['serialNumber'], array_map(function ($item) { return explode(':', trim($item), 2)[1]; }, explode(',', $rawData['extensions']['subjectAltName']))); }
static function certificado_validar_expiracion($certificado) { $data = openssl_x509_parse($certificado); if (self::compare_openssl_date($data['validFrom']) > 0) { throw new toba_error_firma_digital("El certificado no es válido tiene una fecha de inicio superior al día de hoy", "Certificado: {$certificado}"); } if (self::compare_openssl_date($data['validTo']) < 0) { throw new toba_error_firma_digital("El certificado no es válido, tiene una fecha de finalización inferior al día de hoy", "Certificado: {$certificado}"); } }
function check_json($host, $ip, $port) { global $timeout; $data = []; $stream = stream_context_create(array("ssl" => array("capture_peer_cert" => true, "capture_peer_cert_chain" => true, "verify_peer" => false, "peer_name" => $host, "verify_peer_name" => false, "allow_self_signed" => true, "capture_session_meta" => true, "sni_enabled" => true))); if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $connect_ip = "[" . $ip . "]"; } else { $connect_ip = $ip; } $read_stream = stream_socket_client("ssl://{$connect_ip}:{$port}", $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $stream); if ($read_stream === false) { $data["error"] = ["Failed to connect: " . htmlspecialchars($errstr)]; return $data; } else { $context = stream_context_get_params($read_stream); $context_meta = stream_context_get_options($read_stream)['ssl']['session_meta']; $cert_data = openssl_x509_parse($context["options"]["ssl"]["peer_certificate"]); $chain_data = $context["options"]["ssl"]["peer_certificate_chain"]; $chain_length = count($chain_data); if (isset($chain_data) && $chain_length < 10) { $chain_length = count($chain_data); $chain_arr_keys = $chain_data; foreach (array_keys($chain_arr_keys) as $key) { $curr = $chain_data[$key]; $next = $chain_data[$key + 1]; $prev = $chain_data[$key - 1]; $chain_key = (string) $key + 1; if ($key == 0) { $data["connection"] = ssl_conn_metadata_json($host, $ip, $port, $read_stream, $chain_data); $data["chain"][$chain_key] = cert_parse_json($curr, $next, $host, $ip, true); } else { $data["chain"][$chain_key] = cert_parse_json($curr, $next, null, false); } // certificate transparency $ct_urls = ["https://ct.ws.symantec.com", "https://ct.googleapis.com/pilot", "https://ct.googleapis.com/aviator", "https://ct.googleapis.com/rocketeer", "https://ct1.digicert-ct.com/log", "https://ct.izenpe.com", "https://ctlog.api.venafi.com", "https://log.certly.io"]; $data["certificate_transparency"] = []; foreach ($ct_urls as $ct_url) { $submitToCT = submitCertToCT($data["chain"], $ct_url); $ct_result = json_decode($submitToCT, TRUE); if ($ct_result === null && json_last_error() !== JSON_ERROR_NONE) { $result_ct = array('result' => $submitToCT); $data["certificate_transparency"][$ct_url] = $result_ct; } else { $data["certificate_transparency"][$ct_url] = $ct_result; } } } } else { $data["error"] = ["Chain too long."]; return $data; } } return $data; }
protected function downloadCertificate($urlParts) { $streamContext = stream_context_create(["ssl" => ["capture_peer_cert" => TRUE]]); $streamClient = stream_socket_client("ssl://{$urlParts['host']}:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $streamContext); $certificateContext = stream_context_get_params($streamClient); return openssl_x509_parse($certificateContext['options']['ssl']['peer_certificate']); }