Search code examples
phpsslcertificatessl-certificateprivate-key

Certificate and private key do not match when using php to generate certificate signing request


I am facing the problem that a certificate issued by a CA (Microsoft AD Certification service in this case) does not match to the private key that is used to create the certificate request in PHP and I have no idea, how this can be.

Here's my code:

<?php
    $dn = array(
        "countryName" => "NL",
        "stateOrProvinceName" => "state",
        "localityName" => "City",
        "organizationName" => "Company",
        "organizationalUnitName" => "Unit",
        "commonName" => exec("hostname").'.'.exec("hostname -d"),
        "emailAddress" => "mail@example.com"
    );
    
    $res_privkey = openssl_pkey_new();
    openssl_pkey_export_to_file($res_privkey, '/var/www/html/privkey.pem');
            
    $res_csr = openssl_csr_new($dn, $res_privkey);
    openssl_csr_export_to_file($res_csr, '/var/www/html/csr.pem');
?>

I then use csr.pem as a signing request and get a base64 encoded certificate certnew.cer back from my CA. But when I use the private key privkey.pem and the certificate certnew.cer in my apache config I get the apache error message

AH02565: Certificate and private key 127.0.0.1:443:0 from ... and ... do not match

Any ideas?


Solution

  • Not really a solution to the question, but at least a work-around: I changed my php to call a bash script that does the job perfectly:

    <?php
    $key = "/var/www/html/privkey.pem";
        $csr = "/var/www/html/csr.pem";
        $subj = "/C=NL/ST=state/L=City/O=Company/OU=Unit/CN=".exec("hostname").'.'.exec("hostname -d")."/emailAddress=mail@example.com";
        
    exec("sudo ./create_csr.sh $key $csr $subj");
    ?>
    

    And here is the bash script:

    #!/bin/bash
    key=$1
    csr=$2
    subj=$3
    openssl req -new -key $key -out $csr -subj $subj