How to read a digital certificate file with php

5

I have a system in which it does the digital certificate store, I need some information besides the file itself, one of this information is the expiration date of the certificate.

The question is, how to read this file so that I can pick up the expiration date of this certificate?

The certificate is of type A1, and the file extension is in pfx.

I found a solution in this post .

    
asked by anonymous 17.03.2015 / 15:59

2 answers

3

You can use the openssl_x509_parse () function to read the certificate and then return the information in the form of array . For example:

$certpath = "certificado.cer";
$certinfo = openssl_x509_parse(file_get_contents($certpath));
echo "Data de validade: " . $certinfo['validFrom_time_t'];
    
19.03.2015 / 18:38
3

Here is an example of reading the certificate in 'pfx' format, I hope it helps!

<?php
//Caminho do Certificado
$pfxCertPrivado = 'certificado.pfx';
$cert_password  = 'senha';

if (!file_exists($pfxCertPrivado)) {
   echo "Certificado não encontrado!! " . $pfxCertPrivado;
}

$pfxContent = file_get_contents($pfxCertPrivado);

if (!openssl_pkcs12_read($pfxContent, $x509certdata, $cert_password)) {
   echo "O certificado não pode ser lido!!";
} else {

   $CertPriv   = array();
   $CertPriv   = openssl_x509_parse(openssl_x509_read($x509certdata['cert']));

   $PrivateKey = $x509certdata['pkey'];

   $pub_key = openssl_pkey_get_public($x509certdata['cert']);
   $keyData = openssl_pkey_get_details($pub_key);

   $PublicKey  = $keyData['key'];

   echo '<br>'.'<br>'.'--- Dados do Certificado ---'.'<br>'.'<br>';
   echo $CertPriv['name'].'<br>';                           //Nome
   echo $CertPriv['hash'].'<br>';                           //hash
   echo $CertPriv['subject']['C'].'<br>';                   //País
   echo $CertPriv['subject']['ST'].'<br>';                  //Estado
   echo $CertPriv['subject']['L'].'<br>';                   //Município
   echo $CertPriv['subject']['CN'].'<br>';                  //Razão Social e CNPJ / CPF
   echo date('d/m/Y', $CertPriv['validTo_time_t'] ).'<br>'; //Validade
   echo $CertPriv['extensions']['subjectAltName'].'<br>';   //Emails Cadastrados separado por ,
   echo $CertPriv['extensions']['authorityKeyIdentifier'].'<br>'; 
   echo $CertPriv['issuer']['OU'].'<br>';                   //Emissor 
   echo '<br>'.'<br>'.'--- Chave Pública ---'.'<br>'.'<br>';
   print_r($PublicKey);
   echo '<br>'.'<br>'.'--- Chave Privada ---'.'<br>'.'<br>';
   echo $PrivateKey;
}
?>
    
15.02.2017 / 21:09