Reputation: 329
I want to create a RSA key pair in C/C++ and export it to a string to work with it.
I managed to create the key
rsa = RSA_generate_key(bits, exp, NULL, NULL);
if(RSA_check_key(rsa)!=1){
std::cout << "Error while checking key" << std::endl << std::flush;
}
pkey = EVP_PKEY_new();
EVP_PKEY_assign_RSA(pkey, rsa);
From this point I can write the private and public key to a file with PEM_write_PUBKEY() and PEM_write_PrivateKey(). But what I want to do is to get the private and public key from pkey directly into a variable, preferable in the PEM format. I already looked around but couldn't find the right function. Any hints?
Upvotes: 1
Views: 3819
Reputation: 3736
If you really need the PEM representation, then PEM_write_bio_RSA_PUBKEY()
and PEM_write_bio_RSAPrivateKey()
(along with their read
counterparts) are the functions you want; give them memory BIOs to have them write into a memory buffer.
You can create a memory BIO
by invoking e.g.
BIO * b = BIO_new(BIO_s_mem());
and get the memory buffer by invoking
void * buf;
BIO_get_mem_ptr(b, &buf);
You can also create a memory BIO
around existing memory by invoking e.g.
BIO * b = BIO_new_mem_buf(buf, 9001)
but the resulting BIO
will be read-only.
Upvotes: 5