douba4933 2013-09-24 12:30
浏览 205
已采纳

php openssl:如何将私钥与证书相匹配

I have a self signed signature which contains the certificate itself and the private key. My purpose is to check if this private key matches with the certificate. What I do is the following:

$private = openssl_pkey_get_private("path/to/certificate");
$public  = openssl_pkey_get_public("path/to/certificate");
openssl_sign("path/to/certificate", $sig, $private);

So I create the signature based on the private and the public keys from the file. So what I need to do is to compare this signature with the existing signature in the certificate. If they match, it means that the private key matches. However, I couldn't retrieve the existing signature information from the file. I was wondering if my way is a right way to do it since I have found no information on google.

thanks.

  • 写回答

3条回答 默认 最新

  • douao3063 2013-09-25 14:59
    关注

    I have a self signed signature which contains the certificate itself and the private key. My purpose is to check if this private key matches with the certificate. What I do is the following:

    Certificates don't contain private keys. Just public keys. They're signed by a private key (which in the case of self-signed certs would be the private key corresponding to the public key contained in the cert) but they do not contain private keys.

    So what I need to do is to compare this signature with the existing signature in the certificate. If they match, it means that the private key matches.

    They shouldn't ever match. Check out phpseclib's X.509 parser and decode the sample cert they provide with it. There are three parts at the root level. tbsCertificate, signatureAlgorithm and signature. signature is based on tbsCertificate. So you're wanting a signature of tbsCertificate to match a signature of all three fields combined. Which is pretty much never going to happen.

    As for extracting the signature itself... you can use phpseclib for that. eg.

    <?php
    include('File/X509.php');
    
    $x509 = new File_X509();
    $cert = $x509->loadX509('...');
    
    echo $cert['signature']
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?