Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get PEM encoded X509 certificate as C++ string using openssl?

I have a openssl X509 structure with a self signed certificate. I need to get a PEM formatted C++ string from this structure. What are the openssl APIs that I need to use to achieve this?

I tried following the example program at https://www.codeblog.org/gonzui/markup/openssl-0.9.8a/demos/x509/mkcert.c. This program shows a way to write the certificate in PEM format to a file. I can read the contents of this file into a C++ string if there is no other way to do it.

like image 366
jobless Avatar asked Jul 29 '11 18:07

jobless


1 Answers

I have a openssl X509 structure with a self signed certificate. I need to get a PEM formatted C++ string from this structure.

The following should work well for you. Its shows the APIs you need to do it (sans the code to populate the certificate fields).

#include <iostream>
#include <memory>
#include <string>
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::unique_ptr;

#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/x509.h>

using X509_ptr = std::unique_ptr<X509, decltype(&::X509_free)>;
using BIO_MEM_ptr = std::unique_ptr<BIO, decltype(&::BIO_free)>;

int main(int argc, char* argv[])
{
    int rc = 0;
    unsigned long err = 0;

    X509_ptr x509(X509_new(), ::X509_free);
    /* ... */

    BIO_MEM_ptr bio(BIO_new(BIO_s_mem()), ::BIO_free);

    rc = PEM_write_bio_X509(bio.get(), x509.get());
    err = ERR_get_error();

    if (rc != 1)
    {
        cerr << "PEM_write_bio_X509 failed, error " << err << ", ";
        cerr << std::hex << "0x" << err;
        exit(1);
    }

    BUF_MEM *mem = NULL;
    BIO_get_mem_ptr(bio.get(), &mem);
    err = ERR_get_error();

    if (!mem || !mem->data || !mem->length)
    {
        cerr << "BIO_get_mem_ptr failed, error " << err << ", ";
        cerr << std::hex << "0x" << err;
        exit(2);
    }

    string pem(mem->data, mem->length);
    cout << pem << endl;

    return 0;
}

Compile with the following:

g++ -g -O -std=c++11 x509.cpp -o x509.exe \
    -I/usr/local/ssl/include \
    /usr/local/ssl/lib/libcrypto.a -ldl

A typical output is:

$ ./x509.exe 
-----BEGIN CERTIFICATE-----
MCYwHAIBADADBgEAMAAwBB8AHwAwADAIMAMGAQADAQAwAwYBAAMBAA==
-----END CERTIFICATE-----
like image 106
jww Avatar answered Nov 15 '22 09:11

jww