开发者

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

开发者 https://www.devze.com 2023-03-24 09:51 出处:网络
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 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 h开发者_StackOverflow中文版ttps://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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号