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 chose PEM. Now, I have the following function for creating the file
rsa = RSA_new();
// These 3 keys are generated beforehand
rsa->e = e;
rsa->n = n;
rsa->d = d;
fp = fopen(pubkey_file, "w");
if(!PEM_write_RSAPublicKey(fp, rsa))
{
printf("
%s
", "Error writing public key");
}
fflush(fp);
fclose(fp);
fp = fopen(privkey_file, "w");
// pRsaKey = EVP_PKEY_new();
// EVP_PKEY_assign_RSA(pRsaKey, rsa);
if(!PEM_write_RSAPrivateKey(fp, rsa, NULL, 0, 0, NULL, NULL))
// if (!PEM_write_PrivateKey(fp, pRsaKey, NULL, NULL, 0, 0, NULL))
{
printf("
%s
", "Error writing private key");
}
fflush(fp);
fclose(fp);
And this is the function to read the files
rsa = RSA_new();
fp = fopen(pubkey_file, "r");
if(PEM_read_RSAPublicKey(fp, &rsa, NULL, NULL) == NULL)
{
printf("
%s
", "Error Reading public key");
return;
}
fclose(fp);
BN_bn2bin(rsa->n, (unsigned char *)modulus);
BN_bn2bin(rsa->e, (unsigned char *)exp);
printf("
%s
%s
", exp, modulus);
RSA_free(rsa);
// pRsaKey = EVP_PKEY_new();
fp = fopen(privkey_file, "r");
if(fp)
// if((PEM_read_PrivateKey(fp, &pRsaKey, NULL, NULL)) == NULL)
if((PEM_read_RSAPrivateKey(fp, &rsa, NULL, NULL)) == NULL)
{
printf("
%s
", "Error Reading private key");
return;
}
// rsa = RSA_new();
// rsa = EVP_PKEY_get1_RSA(pRsaKey);
fclose(fp);
The public key is written and read as required, but the provate key fails. I have tried writing using both the rsa and the evp(which is commented in the above code). But, both fail. I cannot get my head around why this is happening or try and find where to look to debug this issue. Can anyone please provide some pointers for this?
See Question&Answers more detail:
os