Search code examples
phpsslphpseclib

ssl: match private key with certificat | using php & phpseclib


situation: i have a server-admin-panel, where the user should be able to upload a private key / certificate / ca-certificate ( / CSR) for SSL website protection.

The uploaded data would look like this:

private key =

-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA3u+SI24XGAqIHNLcmCfEFOpMVAOEZOw3DpZ7VexB6soLiu0a
[...]
M9YQw2MV/EhNXTh7PW85HJKAZyTxLJvWIXbEeY9XX+GkqJuQ1GhfgfE=
-----END RSA PRIVATE KEY-----

certificate =

-----BEGIN CERTIFICATE-----
MIIDfjCCAmigAwIBAgIEU6fNGzALBgkqhkiG9w0BAQUwgYExCzAJBgNVBAYMAkRF
[...]
oosSAukE596+wwM0XXDFOT2T/D0lHvW1QVyFx0GzCRHWqQ==
-----END CERTIFICATE-----

problem: after uploading, i need to check, if cert / ca-cert match the private key ( / CSR), to ensure, that all the uploaded parts belong together.


i think i'm stuck. With openssl i could check if the output of the following command matches each other. But i don't know how to do this with phpseclib.

openssl x509 -noout -modulus -in certificate.crt | openssl md5
openssl rsa -noout -modulus -in privateKey.key | openssl md5
openssl req -noout -modulus -in CSR.csr | openssl md5

(i would like to stick with phpseclib, so openssl is not an option)

Thank you very very much!


Solution

  • Something like this do the trick?:

    $rsa = new Crypt_RSA();
    $rsa->loadKey(...);
    $pubkey1 = $rsa->getPublicKey();
    
    $x509 = new File_X509();
    $x509->loadX509(...);
    $pubkey2 = $x509->getPublicKey();
    
    $csr = new File_X509();
    $csr->loadCSR(...);
    $pubkey3 = $csr->getPublicKey();
    
    if (($pubkey1 == $pubkey2) && ($pubkey2 == $pubkey3)) {
        echo "they're equal";
    } else {
        echo "they're not equal";
    }