Hi All,
I would like to confirm whether my approach is correct in initializing
EVP_PKEY from public key DER file and private key DER file.
My question is:
This is the scenario, I have two files; private key files and public key
files. These files are in DER. I would like to initialize the EVP_PKEY with
these two keys for later usage.
I includes a portion of my code that reads initialize the EVP_PKEY.
Currently, I do not read the DER encoded public key into EVP_PKEY if I
already read the DER encoded Private Key (see my ocde snippet).
It seems that the EVP_PKEY public key portion is automatically populated
when the private key is known. Is my understanding correct?
Code snippet:
if((privKeyDER != NULL) && (privKeyDERLen > 0)) // Check whether
DER encoded private key is not NULL or length is not 0
{
/* DER encoded private key is found */
BIO* tempBio = BIO_new_mem_buf(privKeyDER, privKeyDERLen);
if(tempBio == NULL)
{
printf("Error instantiating temp memory BIO for DER
encoded private key\n");
}
else
{
/*
* When private key is known, EVP_PKEY contains both
* Private and Public key.
*/
retEVP_PKEY = d2i_PrivateKey_bio(tempBio, &retEVP_PKEY);
if(retEVP_PKEY == NULL) printf("Error converting DER
encoded private and deriving public key into EVP_PKEY\n");
}
if(tempBio != NULL) BIO_free_all(tempBio);
}
else
{
printf("Null pointer: privKeyDER || privKeyDERLen\n");
printf("only contains public key\n");
}
/* Check if EVP_PKEY has private key */
if(retEVP_PKEY == NULL)
{
/* EVP_PKEY does not have private key */
/* Check if DER encoded public key is there */
/*
* The DER public key is encoded as a SubjectPublicKeyInfo,
so
* d2i_PublicKey can not be used. d2i_PublicKey only
handles RSA public keys encoded
* in the PKCS#1 format. Therefore, use function
d2i_PUBKEY_bio to read the DER key
*/
if((pubKeyDER != NULL) && (pubKeyDERLen > 0))
{
/* DER encoded public key is found */
BIO* tempBio = BIO_new_mem_buf(pubKeyDER, pubKeyDERLen);
if(tempBio == NULL)
{
printf("Error instantiating temp memory BIO for DER
encoded public key\n");
}
else
{
retEVP_PKEY = d2i_PUBKEY_bio(tempBio, &retEVP_PKEY);
if(retEVP_PKEY == NULL) printf("Error converting DER
encoded public key into EVP_PKEY\n");
}
if(tempBio != NULL) BIO_free_all(tempBio);
}
else
{
printf("Null pointer: pubKeyDER || pubKeyDERLen\n");
}
}
/* Check whether EVP_PKEY has either (private and public key) or
(public key) */
if(retEVP_PKEY == NULL)
{
printf("Error converting myKeypair->pubKeyDER into
EVP_PKEY\n");
}
}
Thanks,
Erwin