mouse
mouse

Reputation: 15

How to read and write the public and private key contained in "EVP_PKEY" in a readable way?

I would like to display the public and private key pair contained in "pkey", parameter of the EVP_PKEY_keygen function, in a human readable form, that is, display an encoder key like this for example: 1GERarDJyXsANQqWGGdC3C26GA8K9yMQ7n. Here is a piece of code: generation of parameters and keys :

 EVP_PKEY_CTX *ctx;
EVP_PKEY *pkey = NULL;

ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL);
if(ctx == NULL)
{
  std::cout << "error 1" << std::endl;
}
if(EVP_PKEY_keygen_init(ctx) <= 0)
{
    std::cout << "error 2" << std::endl;
}
if(EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx, NID_X9_62_prime256v1) <= 0)
{
    std::cout << "error 3" << std::endl;
}
if(EVP_PKEY_keygen(ctx, &pkey) <= 0)
{
    std::cout << "error 4" << std::endl;
}
EVP_PKEY_CTX_free(ctx);

My attempt 1 to display the private key contained in "ppkey"

EC_KEY *key;
if(!(key = EVP_PKEY_get1_EC_KEY(pkey)))
{
    std::cout << "error 5" << std::endl;
}
const BIGNUM *prvkey;
if(!(prvkey = EC_KEY_get0_private_key(key)))
{
  std::cout << "error 6" << std::endl;
}
unsigned char *to = NULL;
if(!BN_bn2mpi(prvkey, to))
{
  std::cout << "error 7" << std::endl;
}
 std::cout << *prvkey <<std::endl;

here is the error display :

error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'const BIGNUM' {aka 'const bignum_st'})|

how to display "*ppkey" in std :: cout and correct this error?

My attempt 2 to display the private key contained in "ppkey":

  BIO *bp = NULL;
  if(!EVP_PKEY_print_private(bp, pkey, 1, NULL))
   {
      std::cout << "error 5" << std::endl;
   }
       std::cout << bp <<std::endl;

there the error comes from the function because the condition if is to be respected. How to define well the parameter 3 of the function because I think that the problem comes from that ?

Is there any other function, other method to display and write the keys?

Help me please

Upvotes: 1

Views: 4606

Answers (1)

Matt Caswell
Matt Caswell

Reputation: 9392

You are passing a NULL for the BIO (bp) parameter:

 BIO *bp = NULL;
 if(!EVP_PKEY_print_private(bp, pkey, 1, NULL))

This will cause EVP_PKEY_print_private to fail. The BIO represents the location where you want the key data to be printed, and must be non-NULL. If you just want to print to stdout then you can create it like this:

BIO *bp = BIO_new_fp(stdout, BIO_NOCLOSE);

Be sure to free the BIO up afterwards:

BIO_free(bp);

Upvotes: 2

Related Questions