title: Reading and writing rsa keys to a pem file in C
body: <p>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</p>
  
  <pre><code>rsa = RSA_new();
  // These 3 keys are generated beforehand
  rsa-&gt;e = e;
  rsa-&gt;n = n;
  rsa-&gt;d = d;
  
  fp = fopen(pubkey_file, "w");
  if(!PEM_write_RSAPublicKey(fp, rsa))
  {
      printf("\n%s\n", "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("\n%s\n", "Error writing private key");
  }
  fflush(fp);
  fclose(fp);
  </code></pre>
  
  <p>And this is the function to read the files</p>
  
  <pre><code>rsa = RSA_new();
  fp = fopen(pubkey_file, "r");
  if(PEM_read_RSAPublicKey(fp, &amp;rsa, NULL, NULL) == NULL)
  {
      printf("\n%s\n", "Error Reading public key");
      return;
  }
  
  fclose(fp);
  BN_bn2bin(rsa-&gt;n, (unsigned char *)modulus);
  BN_bn2bin(rsa-&gt;e, (unsigned char *)exp);
  printf("\n%s\n%s\n", exp, modulus);
  RSA_free(rsa);
  
  // pRsaKey = EVP_PKEY_new();
  fp = fopen(privkey_file, "r");
  if(fp)
      // if((PEM_read_PrivateKey(fp, &amp;pRsaKey, NULL, NULL)) == NULL)
      if((PEM_read_RSAPrivateKey(fp, &amp;rsa, NULL, NULL)) == NULL)
      {
          printf("\n%s\n", "Error Reading private key");
          return;
      }
  // rsa = RSA_new();
  // rsa = EVP_PKEY_get1_RSA(pRsaKey);
  fclose(fp);
  </code></pre>
  
  <p>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?</p>