Reputation: 349
Here is the code snippet I have now and it is working well
/* Generate key */
if (EVP_PKEY_keygen(ctx, &pkey) <= 0)
goto cleanup;
// write rsa private key to file
bio_private = BIO_new_file("private_new.pem", "w+");
ret = PEM_write_bio_PrivateKey(bio_private, pkey, NULL, NULL, 0, NULL, NULL);
if (ret != 1) {
goto cleanup;
}
BIO_flush(bio_private);
// write rsa public key to file
bio_public = BIO_new_file("public_new.pem", "w+");
ret = PEM_write_bio_PUBKEY(bio_public, pkey);
if (ret != 1) {
goto cleanup;
}
BIO_flush(bio_public);
instead of using
PEM_write_bio_PrivateKey(bio_private, pkey, NULL, NULL, 0, NULL, NULL);
I want the generated key text to be put into a string and NOT a file. I don't want it written to disk, just to a string in memory. Is there a PEM_ function to do this? or any other way? Thanks a lot for your help
Upvotes: 2
Views: 3112
Reputation: 349
Thanks for Artjom's answer above. It worked! Here is the relevant code with the change :
/* Generate key */
if (EVP_PKEY_keygen(ctx, &pkey) <= 0)
goto cleanup;
// write private key to memory
bio_private = BIO_new(BIO_s_mem());
ret = PEM_write_bio_PrivateKey(bio_private, pkey, NULL, NULL, 0, NULL, NULL);
if (ret != 1)
{
goto cleanup;
}
BIO_flush(bio_private);
BIO_get_mem_data(bio_private, &private_key_text);
cout << "PRIVE KEY :\n" << private_key_text << endl;
// write public key to memory
bio_public = BIO_new(BIO_s_mem());
ret = PEM_write_bio_PUBKEY(bio_public, pkey);
if (ret != 1)
{
goto cleanup;
}
BIO_flush(bio_public);
BIO_get_mem_data(bio_public, &public_key_text);
cout << "PUBLIC KEY :\n" << public_key_text << endl;
Upvotes: 0
Reputation: 61952
Use
bio_private = BIO_new(BIO_s_mem());
instead of
bio_private = BIO_new_file("private_new.pem", "w+");
as seen here.
You can use long BIO_get_mem_data(BIO *b, char **pp)
to access the data in the BIO
:
BIO_get_mem_data() sets pp to a pointer to the start of the memory BIOs data and returns the total amount of data available. It is implemented as a macro.
Upvotes: 4