[Botan-devel] Deriving public key from PEM-encoded private key

Jack Lloyd lloyd at randombit.net
Fri Feb 27 12:37:03 EST 2009


On Thu, Feb 26, 2009 at 10:39:04PM -0500, Z. S. O. wrote:
> My problem is that while it's easy to go from RSA_PrivateKey to std::string,
> I'm not sure how to make the second function because I have no idea how to
> go from std::string to RSA_PrivateKey. I need to have it in that form in
> order to perform X509::PEM_encode to generate the public key.

The function you are looking for is PKCS8::load_key, in pkcs8.h. It
has this signature:

Private_Key* load_key(DataSource& source,
                      RandomNumberGenerator& rng,
                      const std::string& pass = "");

If you know the private key is unencrypted, ignore pass.

DataSource& is where the key is. One subclass of DataSource is
DataSource_Memory, which represents an in-memory object. This
has a std::string constructor.

A simple implementation might look like:

std::string GenPublicKey(std::string privateKey)
   {
   AutoSeeded_RNG rng;
   DataSource_Memory key_src(privateKey);
   Private_Key* pkcs8 = PKCS8::load_key(key_src, rng);
   // You can dynamic_cast pkcs8 to a RSA_PrivateKey* if desired
   return X509::PEM_encode(*pkcs8);
   }

One annoyance is AutoSeeded_RNG is pretty expensive to create (though
some fixes for this are coming in the next release). It would probably
be nice to cache a constructed object and use it repeatedly, however
due to the confluence of a number of factors this is somewhat
obnoxious to implement in practice.

-Jack



More information about the botan-devel mailing list