Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Hello i want my function to write a pem file from my RSA.

void write_privatekey(RSA *rsa, BIO *keybio)
    EVP_PKEY *pkey;
    BIO      *bio_private;
    pkey = PEM_read_bio_PrivateKey(keybio, &pkey, 0, 0);
    bio_private = BIO_new_file("private_new.pem", "w+");
    PEM_write_bio_PrivateKey(bio_private, pkey, NULL, NULL, 0, NULL, NULL);

but when i try to run this code it segfault

[1]    48767 segmentation fault  ./corsair public.key
                The code provided looks badly incomplete.  Where is the RSA private key?  The code makes it looks like the keybio is a BIO referring to a PEM-formatted private key.  But then what is rsa parameter for?  Second, you are doing absolutely zero error checking, which is a recipe for disaster when using OpenSSL libraries. Every last call to an OpenSSL library function needs to have its return value checked for errors. Because chances are the first time you try to use an OpenSSL library function you'll do it wrong - as @datenwolf answered, "The OpenSSL APIs are not the most intuitive to use."
– Andrew Henle
                Jul 23, 2022 at 12:36

The OpenSSL APIs are not the most intuitive to use. However it should be a huge warning sign for you, that you passed a pointer to pkey to PEM_read_bio_PrivateKey and also assign its return value to it.

If you look at the reference manual the suggested stanza is

key = PEM_read_bio_PrivateKey(bp, NULL, pass_cb, …);
if( key == NULL ){
     /* Error */

Your code snipped lacks a couple of things: It doesn't provide a pass phrase callback and it doesn't perform error checking. You absolutely must do both things.

i don't get the warning with my previous code. i did the suggested stanza you mentioned and segfault persist. – Poutite Jul 23, 2022 at 11:49

After messing with the OpenSSL lib. and learned a way to dive into it documentation. here it is the answer to write the PEM file from RSA object.

BIO *bio_private;

bio_private = BIO_new_file("private_new.pem", "w+");
PEM_write_bio_RSAPrivateKey(bio_private, rsa, 0, 0, 0, 0, 0);
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.