Switching from PEM_read_X509 to PEM_read_bio_X509 (FILE based on BIO input)

I'm doing it:

FILE* f_cert = fopen("cert", "rb");
X509* x_cert = NULL;
PEM_read_X509(f_cert, &x_cert, NULL, NULL);
...

Now I want to read this cert file myself and use PEM_read_bio_X509 instead of PEM_read_X509. So, if I already have these variables:

const char cert_data[] = {....};
const int sert_data_size = 123;

How do I initialize a BIO, pass it to PEM_read_bio_X509 and release a temporary biography?

+4
source share
1 answer

Here is a sample code:

const char cert_data[] = {....};
const int cert_data_size = sizeof(cert_data);

BIO *bio = NULL;
X509* x_cert = NULL;

// Create a read-only BIO backed by the supplied memory buffer
bio = BIO_new_mem_buf((void*)cert_data, cert_data_size);

PEM_read_bio_X509(bio, &x_cert, NULL, NULL);
...

// Cleanup
BIO_free(bio);

Note. The data is read directly from the supplied buffer: at first it is not copied, so the memory area must be unchanged until the BIO is freed.

See the OpenSSL documentation in BIO memory for help.

+5
source

All Articles