Reputation: 836
I'd like to print the content of an RSA key created using OpenSSL and accessed by means of the pointer
RSA * rsa;
Now, I've tried to use the RSA_print and BIO_read functions as follows:
BIO * keybio ;
RSA_print(keybio, rsa, 0);
char buffer [1024];
std::string res = "";
while (BIO_read (keybio, buffer, 1023) > 0)
{
std::cout << buffer;
}
but I get a segmentation fault at the very first execution of the BIO_read (sixth line). Can someone spot the error?
Upvotes: 1
Views: 6351
Reputation: 16090
I think you are writing over unallocated memory. I don't think RSA_print()
allocates memory for BIO
, so you are passing an uninitialized pointer to it.
EDIT: As @jww pointed out in the comment, the BIO
object should be instantiated with a set of dedicated options. I edited the answer accordingly. I also changed the buffer size passed to 1024
.
Allocate space:
BIO * keybio = BIO_new(BIO_s_mem());
RSA_print(keybio, rsa, 0);
char buffer [1024];
std::string res = "";
while (BIO_read (keybio, buffer, 1024) > 0)
{
std::cout << buffer;
}
BIO_free(keybio); //appropriate free "method"
BIO_s_mem()
creates a memory BIO
method function. And BIO_new()
creates and initializes the object itself, using the supplied method.
Also please note that this code is c
-style. There is a nice way of wrapping pure pointer into c++
smart pointers, shown here: How to properly print RSA* as string in C++?.
Upvotes: 3