title: Encrypt message using RSA on ESP32
body: <p>What I try to achieve here is to encrypt a message inside ESP32 app built using PlatformIO + Arduino framework.</p>
  <p>After some searchings, I found this repo: <a href="https://github.com/espressif/arduino-esp32" rel="nofollow noreferrer">https://github.com/espressif/arduino-esp32</a></p>
  <p>There is a tool inside it seems able to help me achieve what I want <a href="https://github.com/espressif/arduino-esp32/blob/master/tools/sdk/include/mbedtls/mbedtls/rsa.h" rel="nofollow noreferrer">https://github.com/espressif/arduino-esp32/blob/master/tools/sdk/include/mbedtls/mbedtls/rsa.h</a></p>
  <p>I imported the library &quot;mbedtls&quot; at <a href="https://platformio.org/lib/show/10874/mbedtls" rel="nofollow noreferrer">https://platformio.org/lib/show/10874/mbedtls</a> to the PlatformIO project and start work from there.</p>
  <p>Question: How to load private key file in the app and encrypt the message using the RSA tool?</p>
  <p>What I have currently is:</p>
  <pre class="lang-cpp prettyprint-override"><code>int ret = 1;
  char buf[1024];
  
  mbedtls_pk_init(&amp;pk);
  memset(buf, 0, sizeof(buf));
  
  mbedtls_mpi_init(&amp;N);
  mbedtls_mpi_init(&amp;P);
  mbedtls_mpi_init(&amp;Q);
  mbedtls_mpi_init(&amp;D);
  mbedtls_mpi_init(&amp;E);
  mbedtls_mpi_init(&amp;DP);
  mbedtls_mpi_init(&amp;DQ);
  mbedtls_mpi_init(&amp;QP);
  
  ret = mbedtls_pk_parse_key(&amp;pk, vendorPrivateKey, sizeof(vendorPrivateKey), NULL, NULL);
  
  if (ret != 0) {
    Serial.print(&quot; failed!  mbedtls_pk_parse_key returned: &quot;);
    Serial.print(-ret);
    Serial.println();
  }
  
  if (mbedtls_pk_get_type(&amp;pk) == MBEDTLS_PK_RSA) {
    mbedtls_rsa_context *rsa = mbedtls_pk_rsa(pk);
    
    if ((ret = mbedtls_rsa_export(rsa, &amp;N, &amp;P, &amp;Q, &amp;D, &amp;E)) != 0 
      || (ret = mbedtls_rsa_export_crt(rsa, &amp;DP, &amp;DQ, &amp;QP)) != 0) {
      Serial.println(&quot; failed! could not export RSA parameters.&quot;);
    }
  }
  </code></pre>
  <p>For now I import the private key content directly in char* form (I'm not sure how to import a pem key file into app.) through the header file:
  <code>const unsigned char *vendorPrivateKey = reinterpret_cast&lt;const unsigned char *&gt;(VENDOR_PRIVATE_KEY);</code>
  where the value is stored inside secrets.h</p>
  <p>Then when I ran the program, it yields the following error message for me:
  <code>failed!  mbedtls_pk_parse_key returned: 15616</code></p>
  <p>According to the pk.h file description, this error code 15616 in hexa is 3D00 which indicates <code>/**&lt; Invalid key tag or value. */</code></p>
  <p>Is there any website that provides format checking and see if my private key file fits the requirements of the mbedtls?</p>