title: Openssl RSA encrypt and decrypt in C
body: <p>I've got a sample code that is encrypting a message using PEM private key and decrypting it using PEM public key but at the end the decrypted result is empty.</p>
  
  <pre><code>    const char * msg = "this is a test message";
      //********************Encrypt*******************************
      if ((pFile = fopen("private.pem", "rt")) &amp;&amp;
          (rsa = PEM_read_RSAPrivateKey(pFile, NULL, passwd_callback, (void*)pcszPassphrase)))
      {
          fprintf(stderr, "Private key read.\n");
  
          RSA_private_encrypt(strlen(msg), (unsigned char *)msg, encrypted, rsa, RSA_PKCS1_PADDING);
          fclose(pFile);
      }
      //********************Decrypt*******************************
      pFile = fopen("pubkey.pem", "rt");
      if (rsa = PEM_read_RSAPublicKey(pFile, NULL, NULL, NULL))
      {
          RSA_public_decrypt(strlen((char *)encrypted), encrypted, decrypted, rsa, RSA_PKCS1_PADDING);
          ERR_load_crypto_strings();
          char * err = (char *)malloc(130);
          ERR_error_string(ERR_get_error(), err);
          fprintf(stderr, "Error decrypting message: %s\n", err);
      }
  </code></pre>
  
  <p>as a result the output of RSA_public_decrypt is 1 but decrypted string is empty.</p>
  
  <p>error message : <strong>Error decrypting message: error:0407008A:rsa routines:RSA_padding_check_PKCS1_type_1:invalid padding</strong></p>