Php openssl_x509_parse
This tutorials show you how to use openssl_x509_parse.
The openssl_x509_parse is declared as follows:
openssl_x509_parse( OpenSSLCertificate|string $certificate, bool $short_names = true): array|false
The return value is The structure of the returned data is (deliberately) not yet documented, as it is still subject to change.
Examples
The following code shows how to use openssl_x509_parse.
/* w w w . d e m o 2 s. c o m*/ $cert = openssl_x509_parse($_SERVER['SSL_CLIENT_CERT']); if ($cert) < $dn_cert=$cert["name"]; print "certificat : ".$dn_cert."
\n"; $cert_elements = explode("/",$dn_cert); foreach ($cert_elements as $elem) < if (substr($elem,0,3) == "CN\n"; var_dump($cert); echo "
\n"; if ($uid) < print "uid
\n"; > else < print "authentification par certificat impossible.
\n"; > ?>
/* ww w . d e m o2 s . c o m */ $CONFIGURATION['configargs'] = array ("private_key_bits" => 2048); // ler do ficheiro a chave $fp = fopen("./chave.pem", "r"); $chave = fread($fp, 10000); fclose($fp); $parchaves = openssl_pkey_get_private($chave, null); var_dump($parchaves); // vou criar o DN para o meu certificado $dn = array( "countryName" => "PT", "stateOrProvinceName" => "Lisboa", "localityName" => "Lisboa", "organizationName" => "ISCTE", "organizationalUnitName" => "DCTI", "commonName" => "Carlos Serrao", "emailAddress" => "carlos.serrao@iscte.pt" ); // vou criar o CSR para o meu certificado digital $csr = openssl_csr_new($dn, $parchaves, $CONFIGURATION['configargs']); var_dump($csr); // poderia exportar o CSR para um ficheiro openssl_csr_export_to_file($csr, "./mycsr.pem"); $x509 = openssl_csr_sign($csr, null, $parchaves, 180, $CONFIGURATION['configargs']); // processar e imprimir certificado X.509 para ecran print_r(openssl_x509_parse($x509)); // exportar x.509 para ficheiro openssl_x509_export_to_file($x509, "./mycert.pem"); ?>
// w w w . d e m o 2 s . c o m /* * Copyright (C) 2013 RWW.IO * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished * to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ header('Content-Type: text/plain'); if (isset($_SERVER['SSL_CLIENT_CERT'])) < $pem = $_SERVER['SSL_CLIENT_CERT']; $r = openssl_x509_parse($pem); print_r($r); >
// w w w . d e m o2 s . c o m /** * Copyright (c) 2014 Robin Appelman * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ namespace OC\Security; use OCP\ICertificate; class Certificate implements ICertificate < protected $name; protected $commonName; protected $organization; protected $serial; protected $issueDate; protected $expireDate; protected $issuerName; protected $issuerOrganization; /** * @param string $data base64 encoded certificate * @param string $name * @throws \Exception If the certificate could not get parsed */ public function __construct($data, $name) < $this->name = $name; try < $gmt = new \DateTimeZone('GMT'); $info = openssl_x509_parse($data); $this->commonName = isset($info['subject']['CN']) ? $info['subject']['CN'] : null; $this->organization = isset($info['subject']['O']) ? $info['subject']['O'] : null; $this->issueDate = new \DateTime('@' . $info['validFrom_time_t'], $gmt); $this->expireDate = new \DateTime('@' . $info['validTo_time_t'], $gmt); $this->issuerName = isset($info['issuer']['CN']) ? $info['issuer']['CN'] : null; $this->issuerOrganization = isset($info['issuer']['O']) ? $info['issuer']['O'] : null; > catch (\Exception $e) < throw new \Exception('Certificate could not get parsed.'); > > /** * @return string */ public function getName() < return $this->name; > /** * @return string|null */ public function getCommonName() < return $this->commonName; > /** * @return string */ public function getOrganization() < return $this->organization; > /** * @return \DateTime */ public function getIssueDate() < return $this->issueDate; > /** * @return \DateTime */ public function getExpireDate() < return $this->expireDate; > /** * @return bool */ public function isExpired() < $now = new \DateTime(); return $this->issueDate > $now or $now > $this->expireDate; > /** * @return string|null */ public function getIssuerName() < return $this->issuerName; > /** * @return string|null */ public function getIssuerOrganization() < return $this->issuerOrganization; > >
// w w w . de m o 2 s . c o m /** * Copyright (c) 2014 Robin Appelman * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ namespace OC\Security; use OCP\ICertificate; class Certificate implements ICertificate < protected $name; protected $commonName; protected $organization; protected $serial; protected $issueDate; protected $expireDate; protected $issuerName; protected $issuerOrganization; /** * @param string $data base64 encoded certificate * @param string $name * @throws \Exception If the certificate could not get parsed */ public function __construct($data, $name) < $this->name = $name; try < $gmt = new \DateTimeZone('GMT'); $info = openssl_x509_parse($data); $this->commonName = isset($info['subject']['CN']) ? $info['subject']['CN'] : null; $this->organization = isset($info['subject']['O']) ? $info['subject']['O'] : null; $this->issueDate = new \DateTime('@' . $info['validFrom_time_t'], $gmt); $this->expireDate = new \DateTime('@' . $info['validTo_time_t'], $gmt); $this->issuerName = isset($info['issuer']['CN']) ? $info['issuer']['CN'] : null; $this->issuerOrganization = isset($info['issuer']['O']) ? $info['issuer']['O'] : null; > catch (\Exception $e) < throw new \Exception('Certificate could not get parsed.'); > > /** * @return string */ public function getName() < return $this->name; > /** * @return string|null */ public function getCommonName() < return $this->commonName; > /** * @return string */ public function getOrganization() < return $this->organization; > /** * @return \DateTime */ public function getIssueDate() < return $this->issueDate; > /** * @return \DateTime */ public function getExpireDate() < return $this->expireDate; > /** * @return bool */ public function isExpired() < $now = new \DateTime(); return $this->issueDate > $now or $now > $this->expireDate; > /** * @return string|null */ public function getIssuerName() < return $this->issuerName; > /** * @return string|null */ public function getIssuerOrganization() < return $this->issuerOrganization; > >
Related
demo2s.com | Email: | Demo Source and Support. All rights reserved.
Как прочитать SSL сертификат из PHP
SSL сертификат можно получить с помощью контекста потоков (Stream Context), а разобрать его поможет функция openssl_x509_parse() . Если сертификат отсутствует или просрочен, то код ошибки и текст будет в переменных $err_no и $err_str .
$url = 'ssl://snipp.ru:443'; $context = stream_context_create( array( 'ssl' => array( 'capture_peer_cert' => true, 'verify_peer' => false, // Т.к. промежуточный сертификат может отсутствовать, 'verify_peer_name' => false // отключение его проверки. ) ) ); $fp = stream_socket_client($url, $err_no, $err_str, 30, STREAM_CLIENT_CONNECT, $context); $cert = stream_context_get_params($fp); if (empty($err_no))
Результат:
Array( [name] => /CN=snipp.ru [subject] => Array( [CN] => snipp.ru ) [hash] => d29c8ea7 [issuer] => Array( [C] => US [O] => Let's Encrypt [CN] => Let's Encrypt Authority X3 ) [version] => 2 [serialNumber] => 295366585736462130072577585684820136690675 [serialNumberHex] => 0364011F3441AE879CE07F8A1018FDFA03F3 [validFrom] => 200214143414Z [validTo] => 200514143414Z [validFrom_time_t] => 1581690854 [validTo_time_t] => 1589466854 [signatureTypeSN] => RSA-SHA256 [signatureTypeLN] => sha256WithRSAEncryption [signatureTypeNID] => 668 [purposes] => Array( [1] => Array( [0] => 1 [1] => [2] => sslclient ) [2] => Array( [0] => 1 [1] => [2] => sslserver ) [3] => Array( [0] => 1 [1] => [2] => nssslserver ) [4] => Array( [0] => [1] => [2] => smimesign ) [5] => Array( [0] => [1] => [2] => smimeencrypt ) [6] => Array( [0] => [1] => [2] => crlsign ) [7] => Array( [0] => 1 [1] => 1 [2] => any ) [8] => Array( [0] => 1 [1] => [2] => ocsphelper ) [9] => Array( [0] => [1] => [2] => timestampsign ) ) [extensions] => Array( Openssl x509 parse php => Digital Signature, Key Encipherment [extendedKeyUsage] => TLS Web Server Authentication, TLS Web Client Authentication [basicConstraints] => CA:FALSE [subjectKeyIdentifier] => 93:5E:0E:54:E4:68:87:51:61:07:15:45:04:76:EB:AC:53:69:00:AE [authorityKeyIdentifier] => keyid:A8:4A:6A:63:04:7D:DD:BA:E6:D1:39:B7:A6:45:65:EF:F3:A8:EC:A1 [authorityInfoAccess] => OCSP - URI:http://ocsp.int-x3.letsencrypt.org CA Issuers - URI:http://cert.int-x3.letsencrypt.org/ [subjectAltName] => DNS:snipp.ru, DNS:www.snipp.ru [certificatePolicies] => Policy: 2.23.140.1.2.1 Policy: 1.3.6.1.4.1.44947.1.1.1 CPS: http://cps.letsencrypt.org ) )
Вывод основных данных
echo 'Домен: ' . $info['subject']['CN'] . "\r\n"; echo 'Выдан: ' . $info['issuer']['CN'] . "\r\n"; echo 'Истекает: ' . date('d.m.Y H:i', $info['validTo_time_t']);
Домен: snipp.ru Выдан: Let's Encrypt Authority X3 Истекает: 14.05.2020 17:34
openssl_x509_parse
openssl_x509_parse() returns information about the supplied certificate , including fields such as subject name, issuer name, purposes, valid from and valid to dates etc.
Parameters
X509 certificate. See Key/Certificate parameters for a list of valid values.
short_names controls how the data is indexed in the array — if short_names is true (the default) then fields will be indexed with the short name form, otherwise, the long name form will be used — e.g.: CN is the shortname form of commonName.
Return Values
The structure of the returned data is (deliberately) not yet documented, as it is still subject to change.
Changelog
Version | Description |
---|---|
8.0.0 | certificate accepts an OpenSSLCertificate instance now; previously, a resource of type OpenSSL X.509 was accepted. |
- OpenSSL Functions
- openssl_cipher_iv_length
- openssl_cipher_key_length
- openssl_cms_decrypt
- openssl_cms_encrypt
- openssl_cms_read
- openssl_cms_sign
- openssl_cms_verify
- openssl_csr_export_to_file
- openssl_csr_export
- openssl_csr_get_public_key
- openssl_csr_get_subject
- openssl_csr_new
- openssl_csr_sign
- openssl_decrypt
- openssl_dh_compute_key
- openssl_digest
- openssl_encrypt
- openssl_error_string
- openssl_free_key
- openssl_get_cert_locations
- openssl_get_cipher_methods
- openssl_get_curve_names
- openssl_get_md_methods
- openssl_get_privatekey
- openssl_get_publickey
- openssl_open
- openssl_pbkdf2
- openssl_pkcs12_export_to_file
- openssl_pkcs12_export
- openssl_pkcs12_read
- openssl_pkcs7_decrypt
- openssl_pkcs7_encrypt
- openssl_pkcs7_read
- openssl_pkcs7_sign
- openssl_pkcs7_verify
- openssl_pkey_derive
- openssl_pkey_export_to_file
- openssl_pkey_export
- openssl_pkey_free
- openssl_pkey_get_details
- openssl_pkey_get_private
- openssl_pkey_get_public
- openssl_pkey_new
- openssl_private_decrypt
- openssl_private_encrypt
- openssl_public_decrypt
- openssl_public_encrypt
- openssl_random_pseudo_bytes
- openssl_seal
- openssl_sign
- openssl_spki_export_challenge
- openssl_spki_export
- openssl_spki_new
- openssl_spki_verify
- openssl_verify
- openssl_x509_check_private_key
- openssl_x509_checkpurpose
- openssl_x509_export_to_file
- openssl_x509_export
- openssl_x509_fingerprint
- openssl_x509_free
- openssl_x509_parse
- openssl_x509_read
- openssl_x509_verify