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

我与影子孤独终老i 提交于 2019-12-24 10:48:37

问题


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.


回答1:


look at the source of the openssl x509 command and see how it does the operation to read a DER encoded file and writes a PEM one - ie:

openssl x509 -in mycert.der -inform DER -out mycert.pem

The code of the cli utils is pretty easy to follow




回答2:


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-----


来源:https://stackoverflow.com/questions/39968558/convert-openssl-x509-data-to-stdstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!