title: RSA public encryption using public key from X509 certificate c++
body: <p>The task is to encrypt some message with RSA public key which lies in .crt file - X509 certificate file.</p>
  
  <p>With issue below I succesfully get sertificate information, but can not find any issue how to use public key from <strong>x</strong> to encrypt message using RSA algorythm.</p>
  
  <p>When I trying to create BIO buffer with key data and to use <strong>PEM_read_bio_RSA_PUBKEY</strong> function to write key into <strong>RSA</strong> struct it returns an error <strong>"error:0906D06C:PEM routines:PEM_read_bio:no start line"</strong> which is clear why appear but not clear how to correctly solve. Are any issue how I can do encryption without creating another buffer and adding manualy lines with <strong>"-----BEGIN RSA PUBLIC KEY-----"</strong> and <strong>"-----END RSA PUBLIC KEY-----"</strong>?</p>
  
  <p>Here are my code for this job:</p>
  
  <pre><code>unsigned char message[] = "Hello cryptographic world!";
  unsigned char *encrypted_text;
  
  int CyferWithHostKeyPub()
  {
      ERR_load_crypto_strings();
  
      int res_length = 0;
  
      RSA *public_key;
      X509 *x;
      BIO *fp = BIO_new_file("cert.crt", "r");
  
      if (!fp)
      {
          printf("\nCan't open file.\n");
          return -1;
      }
  
      x = PEM_read_bio_X509(fp, 0, 0, NULL);
  
      if (!x) {
          printf("%s\n", ERR_error_string(ERR_get_error(), NULL));
          return 1;
      }
  
      BIO *membuf = BIO_new_mem_buf((void*)x-&gt;cert_info-&gt;key-&gt;public_key-&gt;data, x-&gt;cert_info-&gt;key-&gt;public_key-&gt;length);
  
      public_key = PEM_read_bio_RSA_PUBKEY(membuf, &amp;public_key, NULL, NULL);
      if (!public_key) {
          printf("%s\n", ERR_error_string(ERR_get_error(), NULL));
          return 1;
      }
  
      int encrypted_length = RSA_size(public_key);
      encrypted_text = new unsigned char[ encrypted_length ];
      RSA_public_encrypt(sizeof(message), message, encrypted_text, public_key, RSA_PKCS1_PADDING);
  
      RSA_free(public_key);
      X509_free(x);
      BIO_free(membuf);
      BIO_free(fp);
  
      return encrypted_length;
  }
  </code></pre>
  
  <p>So, how can I do this correctly? Thanks!</p>