I am writing a C program to generate keys for RSA and write them to a file and then read from them. The homework requires me to generate the files in a openssl format. So, I
The answer given by sirgeorge has a mistake in the Code.
The create_rsa_key
should not be called twice. If it is called twice then private key does not have matching public key. This results in problems during decryption.
Modifications needed in main
method
RSA *pRSA = NULL;
pRSA = RSA_generate_key(2048,RSA_3,gen_callback,NULL);
pPrivKey = create_rsa_key(pRSA);
pPubKey = create_rsa_key(pRSA);
Modifications needed in create_rsa_key
EVP_PKEY* create_rsa_key(RSA *pRSA)
{
EVP_PKEY* pKey = NULL;
pKey = EVP_PKEY_new();
if(pRSA && pKey && EVP_PKEY_assign_RSA(pKey,pRSA))
{
/* pKey owns pRSA from now */
if(RSA_check_key(pRSA) <= 0)
{
fprintf(stderr,"RSA_check_key failed.\n");
handle_openssl_error();
EVP_PKEY_free(pKey);
pKey = NULL;
}
}
else
{
handle_openssl_error();
if(pRSA)
{
RSA_free(pRSA);
pRSA = NULL;
}
if(pKey)
{
EVP_PKEY_free(pKey);
pKey = NULL;
}
}
return pKey;
}