Search code examples
phpopensslphp-openssl

Is it possible to convert rsa public key to x509 public key?


I have following public key:

-----BEGIN RSA PUBLIC KEY-----
... key ...
-----END RSA PUBLIC KEY-----

PHP can't work with that public key. I found that it should be in x509 format to be usable in php. Is it possible to convert this key to x509 format? As i understand result should look like:

-----BEGIN PUBLIC KEY-----
... changed? key ...
-----END PUBLIC KEY-----

UPD: Exactly it was necessary to generate x509 certificate, not just public key.


Solution

  • phpseclib, a pure PHP RSA library, can work with RSA keys of that format just fine.

    That said, with regard to openssl, you are right - RSA public keys need to be encapsulated in X.509 certs to work with most openssl_* functions.

    From the phpseclib interoperability documentation:

    // openssl_get_publickey() only creates public key resources from X.509
    // certificates hence our creating one
    $dn = array();  // use defaults
    $res_privkey = openssl_pkey_get_private($privkey);
    $res_csr = openssl_csr_new($dn, $res_privkey);
    $res_cert = openssl_csr_sign($res_csr, null, $res_privkey, 365);
    openssl_x509_export($res_cert, $str_cert);
    $res_pubkey = openssl_get_publickey($str_cert);
    

    That said the result shouldn't look like what you posted but rather like this:

    -----BEGIN CERTIFICATE-----
    ...
    -----END CERTIFICATE-----