Parse EC Public key

1.4k views Asked by At

I an working on ECIES and need to load peer public key. Load EC Public key

I an using ECDH and need to load peer public key. When I try to load public key from PEM file , seems no issue

Issue here:

EVP_PKEY * get_peer_key()  
{
     // base64 certificate data of alice_pub_key.pem
     char *buffer= "MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEjWrT7F97QrSqGrlIgPK8dphNBicNO6gDLfOIMjhF2MiLuuzd7L7BP+bLCuNtKKe/2dOkgPqgXv4BFWqgp6PZXQ=="`
     // calculate buffer length
     int l = strlen(buffer)
     //create bio from buffer
     BIO *in = BIO_new_mem_buf(buffer,l)
     //gnerate ec key   
     EC_KEY *eckey = PEM_read_bio_EC_PUBKEY(in,NULL,NULL,NULL)` // ==> FAIL
     //need to convert to EVP format
     EVP_PKEY *peerKey = EVP_PKEY_new()
     //assign ec key evp
     if(EVP_PKEY_assign_EC_KEY(peerKey,eckey) != 1 )
         printf("\n error hapened");
     return peerKey;
}

Works fine:

EVP_PKEY * get_peer_key()
{
     //Load PEM format file
     char * infile = "alice_pub_key.pem";
     //create bio
     BIO *in = BIO_new(BIO_s_file());
     //read bio file
     BIO_read_filename(in , infile);
     //create eckey
     EC_KEY *eckey = PEM_read_bio_EC_PUBKEY(in,NULL,NULL,NULL); // ==> success
     // create peer key   
     EVP_PKEY *peerKey = EVP_PKEY_new();
     //assign public key
     if(EVP_PKEY_assign_EC_KEY(peerKey,eckey) != 1 )
         printf("\n error hapened");
     return peerKey;
}

Can some one suggest whats going wrong while reading base64 data of pem file

1

There are 1 answers

3
Maarten Bodewes On

There are two ways of solving this:

  1. Creating a PEM using a header and footer line and line breaks (at the 64th character;
  2. Base 64 decoding the text and then handling it by parsing the resulting ASN.1 / DER binary;

I'd prefer the latter, as I abhor adding lines and such, it is error prone at best, and string manipulations should be avoided where possible.

Note that this assumes that the base 64 contains a SubjectPublicKeyInfo structure which I've shown you earlier. Otherwise you may have to find out how to parse a X9.62 structure or just a point.