[Botan-devel] Importing (SSLeay format) DSA privateKey

Jack Lloyd lloyd at randombit.net
Tue Jan 27 20:01:03 EST 2009

On Tue, Jan 27, 2009 at 01:35:06PM -0600, Daniel Gollas Gilman wrote:
> Hi, I have a private key generated using OpenSSL but I can't figure out how to 
> load it.

The easiest/best way would be to convert it from SSLeay format to PKCS #8 using
OpenSSL's pkcs8 utility

$ cat dsa.pem | openssl pkcs8 -topk8 -nocrypt

Otherwise probably the thing to do is use the BER decoder:

#include <botan/botan.h>
#include <botan/dsa.h>
#include <botan/pem.h>
#include <botan/ber_dec.h>
#include <stdexcept>

using namespace Botan;

DSA_PrivateKey* load_ssleay_dsa(const std::string& file,
                                RandomNumberGenerator& rng)
   DataSource_Stream input(file);
   std::string pem_label;
   SecureVector<byte> key_bits = PEM_Code::decode(input, pem_label);
   if(pem_label != "DSA PRIVATE KEY")
      return 0;

   DataSource_Memory key_source(key_bits);

   BER_Decoder ber(key_source);

   BigInt version, p, q, g, y, x;

   BER_Decoder key_data = ber.start_cons(SEQUENCE);


   if(version != 0)
      throw std::invalid_argument("Unexpected version # in SSLeay DSA key file");

   DL_Group group(p, q, g);

   DSA_PrivateKey* dsa = new DSA_PrivateKey(rng, group, x);

   if(dsa->get_y() != y)
      throw std::logic_error("Computed DSA public key did not match SSLeay value");

   return dsa;

#include <iostream>
#include <iomanip>

int main()
   LibraryInitializer init;

   AutoSeeded_RNG rng;

   DSA_PrivateKey* dsa = load_ssleay_dsa("dsa.pem", rng);

   std::cout << std::hex << dsa->get_x() << '\n';

More information about the botan-devel mailing list