3

I have this code:

int importKey(){

FILE *fp=NULL;
RSA *pkey=NULL;
R_RSA_PRIVATE_KEY prk; //special structure

fp = fopen("sslcert/key.pem", "r");

fseek(fp, 0, SEEK_SET);
PEM_read_RSAPrivateKey(fp, &pkey, NULL, NULL);

if (!pkey)
{
    fseek(fp, 0, SEEK_SET);
    d2i_RSAPrivateKey_fp(fp, &pkey);
}

prk.bits=BN_num_bits(pkey->n);
return pkey; //check if pkey==0 or something else
}

This works just fine when I give .pem file to fp what I created from command line using openssl -pkcs12 -in file.pfx -out key.pem. But what I need is to use that pfx file in fp = fopen() and somehow "extract" private key inside code and save it into that RSA *pkey and also extract certificate from the same pfx file and save it into X509 *px509 variable. Any help with that?

Meaning I need in fact some openssl functions to do the some routine as that command line command

SysDragon
  • 9,692
  • 15
  • 60
  • 89
Raadush
  • 71
  • 1
  • 9
  • PEM is actualy a base64 encoding with some header. U can read the pfx file and do a base64 encode(Available in net), then append headers before calling the function. A tag -----BEGIN RSA PRIVATE KEY----- will be present before PEM data and a -----END RSA PRIVATE KEY----- will be present after the base64 data. – DAC84 May 22 '12 at 12:54
  • Duplicate? http://stackoverflow.com/questions/6371775/how-to-load-a-pkcs12-file-in-openssl-programmatically – Jay May 22 '12 at 13:03
  • 2
    No, its not duplicate, but I managed to solve my problem thanks to this post. Problem was that in [link](http://stackoverflow.com/questions/6371775/how-to-load-a-pkcs12-file-in-openssl-programmatically) key was saved into EVP_PKEY variable and I needed to have key in RSA variable. But then I found openssl conversion function: `pkey = EVP_PKEY_get1_RSA(evp_key);` and it's working like charm now. Thanks for pointing me right direction ;) – Raadush May 22 '12 at 13:40

0 Answers0