How to fix esp-tls-mbedtls: mbedtls_x509_crt_parse returned -0x2180


While trying to use TLS on the ESP32, you are using a certificate and private key e.g. from NVS or from the filesystem. However when you try to connect using SSL, you see error messages like

E (9774) esp-tls-mbedtls: mbedtls_x509_crt_parse returned -0x2180
E (9775) esp-tls-mbedtls: Failed to set server pki context
E (9775) esp-tls-mbedtls: Failed to set server configurations, returned [0x8015] (ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED)
E (9786) esp-tls-mbedtls: create_ssl_handle failed, returned [0x8015] (ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED)
E (9795) esp_https_server: esp_tls_create_server_session failed



The most common issue here is that conf.cacert_len and conf.prvtkey_len must include the NUL terminator in the length.

Working Example:

conf.cacert_pem = (const uint8_t*)cert.c_str();
conf.cacert_len = this->cert.size() + 1;

conf.prvtkey_pem = (const uint8_t*)privkey.c_str();
conf.prvtkey_len = this->privkey.size() + 1;

Note the + 1 here: Without the + 1, you’ll see the mbedtls_x509_crt_parse returned -0x2180

Other causes:

If the length isn’t the issue, you likely have a malformed certificate. I suggest to print out the certificate’s content via the serial port, saving it to file we’ll call cert_esp32.pem and then running

openssl x509 -in cert_esp32.pem -noout -text

to verify that the certificate is correct. You can do the same for the private key, but typically either both the private key and the certificate are fine or both are not.