读取并解析.cer文件

时间:2014-10-30 18:51:46

标签: php ssl

我有证书(.cer)我必须阅读证书的基本信息,如失效日期。

我在php中编写了这段代码

class FirmaElectronica {
    public function abrirCertificado( $path ){

        $cert_content = file_get_contents( $path );


        $res = openssl_x509_read( $cert_content );

        $data = openssl_x509_parse( $res );
        var_dump( $data );
    }
}

$firma = new FirmaElectronica();
$firma->abrirCertificado('gohl881206rga.cer');

但总是得到这个警告和一个空的数据数组

PHP Warning:  openssl_x509_read(): supplied parameter cannot be coerced into an X509 certificate!

如果我执行此命令,我将获得所有证书数据

openssl x509 -in gohl881206rga.cer -noout -text -inform der

使用php获取证书数据的正确方法是什么?

3 个答案:

答案 0 :(得分:3)

使用phpseclib ..

<?php
include('File/X509.php');

$x509 = new File_X509();
$cert = $x509->loadX509('...');

echo $cert['tbsCertificate']['validity']['notBefore'] . "\r\n";
echo $cert['tbsCertificate']['validity']['notAfter'];

如果这不起作用,您是否可以发布您尝试从中获取此信息的实际证书?

答案 1 :(得分:0)

确定。要解决此问题,您需要确保拥有cer(或pem)的私钥。

回答

1导出证书和密钥到.p12

在OSX上例如:打开钥匙串 - &gt;选择您的证书和包含密钥 - &gt;按住Ctrl键单击导出 - &gt;导出2个对象。

2转换证书:

 openssl pkcs12 -in cert.p12 -out cert.pem -nodes -clcerts

3安全

cat cert.pem 
你应该看到类似的东西:

Bag Attributes
    friendlyName: blablub
    localKeyID: SOME ID HERE
subject=/UID=(name)/CN=(a name)/OU=(a id)/C=(locale)
issuer=/C=(locale)/O=(auth)/OU=(authname)/CN=(name)
-----BEGIN CERTIFICATE-----
ABCD.....(cert here).....
-----END CERTIFICATE-----
Bag Attributes
    friendlyName: blubbla
    localKeyID: SOME ID HERE 
Key Attributes: <No Attributes>
-----BEGIN RSA PRIVATE KEY-----
AB....(key here)....
-----END RSA PRIVATE KEY-----

现在你已准备好使用原始代码而不使用php中的另一个lib:

 $cert_content = file_get_contents( $path );
 $res = openssl_x509_read( $cert_content );

答案 2 :(得分:0)

我知道这个问题已经过时,但我想分享这个问题的可能解决方案。

  

首先:我有同样的问题。证书是正确的,我的PHP   代码也是。

我发现问题是证书的格式化。为了解决这个问题,我创建了一个函数并正确编辑了证书:

function createCertificate($cert) {

        $a = "-----BEGIN CERTIFICATE-----\n";
        $b = "\n-----END CERTIFICATE-----";

        $withoutFirsLine = substr($cert, strlen('-----BEGINCERTIFICATE-----'));

        $count = (strlen($withoutFirsLine) - strlen('-----ENDCERTIFICATE-----'));
        $withoutFirstAndLastLine = substr($withoutFirsLine, 0, $count);

        $withoutFirstAndLastLine = wordwrap($withoutFirstAndLastLine, 64, "\n", true);

        return $a.$withoutFirstAndLastLine . $b;

}

我希望我可以帮助其他有同样问题的人!