Search code examples
c++copensslcertificatex509

How to get the base64 encoded certificate (PEM) from connected ssl session


I am using the following to get the PEM certificate for a connected session in openssl C. What I need is to get a base64 encoded certificate.

if(this->ssl) {
  X509 *cert = SSL_get_certificate(this->ssl);
  EVP_PKEY *pubKey = X509_get_pubkey(cert);
  LOG_INFO("Public key is " << BN_bn2hex(pubKey->pkey.rsa->n));
}

Any information on how can I achieve this would be helpful.


Solution

  • You should use i2d_X509 function to get DER encoded certificate. Then use your favorite base64 encoder and encode it to PEM. Do not forget to add -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- if you want it proper way.

    Here you may find example on how to encode with OpenSSL itself. In using OpenSSL you may simplify things by using i2d_X509_bio function to put DER encoded data directly into BIO.