TheSVchaos
TheSVchaos

Reputation: 31

Any way to get length of printable version of a X509 certificate (that is printed by X509_print* openssl function)?

I want to get size of text that will be printed by [email protected](c-g) X509_print function. I need this to allocate appropriate memory buffer for memory BIO and send the BIO to X509_print function.

I know I can use a buffer large enough for this, but is there any way to get exact size without explicit parsing the X509 certificate like in the X509_print* functions?

I have the same question regarding the data size printed by PEM_write_X509.

Upvotes: 0

Views: 350

Answers (1)

TheSVchaos
TheSVchaos

Reputation: 31

Finally:

BIO structure has a field num_write. It is length of byte representation of data in a BIO. However this field is hidden normally. But we can get it via function BIO_number_written from <openssl/bio.h>.

Note: for char strings it may not count the terminating byte.

Below is sample code (necessary to add NULL and fail checks):

    X509 *x509 = NULL;
    BIO *bio = NULL;
    char *str = NULL;
...
    bio = BIO_new(BIO_s_mem());
    X509_print(bio, x509);
    ptr = malloc(BIO_number_written(bio) + 1);
    ptr[BIO_number_written(bio)] = 0;
    BIO_read(bio, ptr, BIO_number_written(bio));
...

Upvotes: 1

Related Questions