Home / References / ESP32 Library / WiFiClientSecure
Description
The setCACert()
method in the ESP32 WiFiClientSecure Library sets the Certificate Authority (CA) certificate for a secure network connection. This method is essential for makers and enthusiasts building secure IoT projects with the ESP32, as it enables verification of a server’s identity during an SSL/TLS handshake. By providing a trusted CA certificate, you ensure encrypted communication is both safe and reliable, empowering you to create robust, secure applications.
Syntax and Usage
The setCACert()
method has a single usage with one argument. Here’s how to incorporate it into your ESP32 sketches:
client.setCACert(ca_cert);
This method is called on a WiFiClientSecure
object before establishing a secure connection. It configures the client to use the specified CA certificate to validate the server’s certificate, ensuring a trusted connection.
Argument(s)
The setCACert()
method requires one argument:
ca_cert
(const char*): A pointer to a null-terminated string containing the PEM-encoded CA certificate. This certificate is used to verify the server’s identity during the SSL/TLS handshake.
For practical applications and examples of this method, please consult the “Example Code” section on this page. This section provides comprehensive guidance to help you better understand and apply the method effectively.
Return Value
The setCACert()
method does not return a value (i.e., it is a void
function). Its purpose is to configure the client’s CA certificate for secure connections, and its success is reflected in the subsequent connection attempt.
Example Codes
Below is an example demonstrating how to use setCACert()
in a practical ESP32 project. This example connects to a secure server and uses a sample CA certificate.
Example 1: Connecting to a Secure Server with a CA Certificate
This sketch connects to a secure test server (www.httpbin.org
) using setCACert()
to set a CA certificate, ensuring a verified SSL/TLS connection.
ATTENTION: The Root CA certificate has an expiration date. If the code fails to execute, it may be due to the Root CA certificate has expired. Try obtaining the latest Root CA certificate and replacing the expired one in this code. For detailed instructions on acquiring a website’s Root CA certificate, check out the link below:
How to Acquire the Root CA Certificate
/*
* Author: Avant Maker
* Date: March 6, 2025
* Version: 1.0
*
* Description: This example demonstrate how to use
* ESP32 WiFiClientSecure Libary's
* setCACert method to set a CA certificate,
* ensuring a verified SSL/TLS connection.
*
* ATTENTION: The Root CA certificate has an expiration date.
* If the code fails to execute, it may be due to the Root CA
* certificate has expired. Try obtaining the latest
* Root CA certificate and replacing the expired one in this code.
* For detailed instructions on acquiring a website's
* Root CA certificate, check out the link below:
*
* https://avantmaker.com/references/esp32-arduino-core-index/esp32-wificlientsecure-library/how-to-acquire-the-root-ca-certificate/
*
* License: MIT
*
* Code Source: This example code is sourced from the Comprehensive
* Guide to the ESP32 Arduino Core Library, accessible on
* AvantMaker.com. For additional code examples and in-depth
* documentation related to the ESP32 Arduino Core Library,
* please visit:
*
* https://avantmaker.com/references/esp32-arduino-core-index/
*
* AvantMaker.com, your premier destination for all things
* DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
* to empowering makers, learners, and enthusiasts with the resources
* they need to bring their innovative ideas to life.
*/
#include <WiFi.h>
#include <NetworkClientSecure.h>
const char* ssid = "your_SSID"; // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD"; // Replace with your Wi-Fi password
const char* host = "www.httpbin.org";
const int port = 443;
const char* rootCACert = R"EOF(
-----BEGIN CERTIFICATE-----
MIIEXjCCA0agAwIBAgITB3MSSkvL1E7HtTvq8ZSELToPoTANBgkqhkiG9w0BAQsF
ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6
b24gUm9vdCBDQSAxMB4XDTIyMDgyMzIyMjUzMFoXDTMwMDgyMzIyMjUzMFowPDEL
MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEcMBoGA1UEAxMTQW1hem9uIFJT
QSAyMDQ4IE0wMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALtDGMZa
qHneKei1by6+pUPPLljTB143Si6VpEWPc6mSkFhZb/6qrkZyoHlQLbDYnI2D7hD0
sdzEqfnuAjIsuXQLG3A8TvX6V3oFNBFVe8NlLJHvBseKY88saLwufxkZVwk74g4n
WlNMXzla9Y5F3wwRHwMVH443xGz6UtGSZSqQ94eFx5X7Tlqt8whi8qCaKdZ5rNak
+r9nUThOeClqFd4oXych//Rc7Y0eX1KNWHYSI1Nk31mYgiK3JvH063g+K9tHA63Z
eTgKgndlh+WI+zv7i44HepRZjA1FYwYZ9Vv/9UkC5Yz8/yU65fgjaE+wVHM4e/Yy
C2osrPWE7gJ+dXMCAwEAAaOCAVowggFWMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYD
VR0PAQH/BAQDAgGGMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAdBgNV
HQ4EFgQUwDFSzVpQw4J8dHHOy+mc+XrrguIwHwYDVR0jBBgwFoAUhBjMhTTsvAyU
lC4IWZzHshBOCggwewYIKwYBBQUHAQEEbzBtMC8GCCsGAQUFBzABhiNodHRwOi8v
b2NzcC5yb290Y2ExLmFtYXpvbnRydXN0LmNvbTA6BggrBgEFBQcwAoYuaHR0cDov
L2NydC5yb290Y2ExLmFtYXpvbnRydXN0LmNvbS9yb290Y2ExLmNlcjA/BgNVHR8E
ODA2MDSgMqAwhi5odHRwOi8vY3JsLnJvb3RjYTEuYW1hem9udHJ1c3QuY29tL3Jv
b3RjYTEuY3JsMBMGA1UdIAQMMAowCAYGZ4EMAQIBMA0GCSqGSIb3DQEBCwUAA4IB
AQAtTi6Fs0Azfi+iwm7jrz+CSxHH+uHl7Law3MQSXVtR8RV53PtR6r/6gNpqlzdo
Zq4FKbADi1v9Bun8RY8D51uedRfjsbeodizeBB8nXmeyD33Ep7VATj4ozcd31YFV
fgRhvTSxNrrTlNpWkUk0m3BMPv8sg381HhA6uEYokE5q9uws/3YkKqRiEz3TsaWm
JqIRZhMbgAfp7O7FUwFIb7UIspogZSKxPIWJpxiPo3TcBambbVtQOcNRWz5qCQdD
slI2yayq0n2TXoHyNCLEH8rpsJRVILFsg0jc7BaFrMnF462+ajSehgj12IidNeRN
4zl+EoNaWdpnWndvSpAEkq2P
-----END CERTIFICATE-----
)EOF";
// Optional: Add client certificate and key for mutual TLS if needed
// const char* clientCertKey = "";
// const char* clientCert = "";
NetworkClientSecure secureClient;
void setup() {
Serial.begin(115200);
// Connect WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to WiFi");
// Set the Root CA Cert
secureClient.setCACert(rootCACert);
// Establish secure connection to server
if (secureClient.connect(host, port)) {
Serial.println("Connected to server");
// Create the POST data
String postData = "AvantMaker=HelloFromESP32";
// Send the POST request
secureClient.print("POST /post HTTP/1.1\r\n");
secureClient.print("Host: www.httpbin.org\r\n");
secureClient.print("Content-Type: application/x-www-form-urlencoded\r\n");
secureClient.print("Content-Length: ");
secureClient.print(postData.length());
secureClient.print("\r\nConnection: close\r\n\r\n");
secureClient.print(postData);
// Wait for server response
while (secureClient.connected() && !secureClient.available()) {
delay(10);
}
// Read response
if (secureClient.available()) {
String response = secureClient.readString();
Serial.print("Server response:\n");
Serial.println(response);
} else {
Serial.println("No data available");
}
secureClient.stop();
} else {
Serial.println("Failed to connect to server! Check the code description for solution.");
return;
}
}
void loop() {
}
Explanation: In this example, the ESP32 connects to www.httpbin.org
over HTTPS. Before connecting, setCACert()
is called with a placeholder CA certificate (in PEM format) to enable server verification. The sketch then sends a GET request and prints the response. For real projects, replace the placeholder with the actual CA certificate for your server, obtainable from its certificate chain. This demonstrates how setCACert()
ensures a secure, trusted connection.
Example 2: Connecting to more than one Secure Servers with CA Certificates
This example code demonstrates how to use ESP32 WiFiClientSecure Library’s setCACert method to setup more than one CA cert and let ESP32 securely connect to more than one server (one server at a time).
ATTENTION: The Root CA certificate has an expiration date. If the code fails to execute, it may be due to the Root CA certificate has expired. Try obtaining the latest Root CA certificate and replacing the expired one in this code. For detailed instructions on acquiring a website’s Root CA certificate, check out the link below:
How to Acquire the Root CA Certificate
/*
* Author: Avant Maker
* Date: February 24, 2025
* Version: 1.0
*
* Description: This example demonstrate how to use
* ESP32 WiFiClientSecure Libary's
* setCACert method to securely connect to more than
* one severs (one sever at a time) in one code.
*
* ATTENTION: The Root CA certificate has an expiration date.
* If the code fails to execute, it may be due to the Root CA
* certificate has expired. Try obtaining the latest
* Root CA certificate and replacing the expired one in this code.
* For detailed instructions on acquiring a website's
* Root CA certificate, check out the link below:
*
* https://avantmaker.com/references/esp32-arduino-core-index/esp32-wificlientsecure-library/how-to-acquire-the-root-ca-certificate/
*
* License: MIT
*
* Code Source: This example code is sourced from the Comprehensive
* Guide to the ESP32 Arduino Core Library, accessible on
* AvantMaker.com. For additional code examples and in-depth
* documentation related to the ESP32 Arduino Core Library,
* please visit:
*
* https://avantmaker.com/references/esp32-arduino-core-index/
*
* AvantMaker.com, your premier destination for all things
* DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
* to empowering makers, learners, and enthusiasts with the resources
* they need to bring their innovative ideas to life.
*/
#include <WiFi.h>
#include <NetworkClientSecure.h>
const char* ssid = "your-SSID"; // Replace with your Wi-Fi SSID
const char* password = "your-PASSWORD"; // Replace with your Wi-Fi password
const char* host = "www.httpbin.org";
const char* host2 = "www.howsmyssl.com";
const int port = 443;
// Root CA certificate for www.httpbin.org (update with your server's CA if different)
const char* caCertBundlePEM = R"literal(
-----BEGIN CERTIFICATE-----
MIIEXjCCA0agAwIBAgITB3MSSkvL1E7HtTvq8ZSELToPoTANBgkqhkiG9w0BAQsF
ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6
b24gUm9vdCBDQSAxMB4XDTIyMDgyMzIyMjUzMFoXDTMwMDgyMzIyMjUzMFowPDEL
MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEcMBoGA1UEAxMTQW1hem9uIFJT
QSAyMDQ4IE0wMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALtDGMZa
qHneKei1by6+pUPPLljTB143Si6VpEWPc6mSkFhZb/6qrkZyoHlQLbDYnI2D7hD0
sdzEqfnuAjIsuXQLG3A8TvX6V3oFNBFVe8NlLJHvBseKY88saLwufxkZVwk74g4n
WlNMXzla9Y5F3wwRHwMVH443xGz6UtGSZSqQ94eFx5X7Tlqt8whi8qCaKdZ5rNak
+r9nUThOeClqFd4oXych//Rc7Y0eX1KNWHYSI1Nk31mYgiK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HKNY67u4s5Lzzfd
u6PUzeetUK29v+PsPmI2cJkxp+iN3epi4hKu9ZzUPSwMqtCceb7qPVxEbpYxY1p9
1n5PJKBLBX9eb9LU6l8zSxPWV7bK3lG4XaMJgnT9x3ies7msFtpKK5bDtotij/l0
GaKeA97pb5uwD9KgWvaFXMIEt8jVTjLEvwRdvCn294GPDF08U8lAkIv7tghluaQh
1QnlE4SEN4LOECj8dsIGJXpGUk3aU3KkJz9icKy+aUgA+2cP21uh6NcDIS3XyfaZ
QjmDQ993ChII8SXWupQZVBiIpcWO4RqZk3lr7Bz5MUCwzDIA359e57SSq5CCkY0N
4B6Vulk7LktfwrdGNVI5BsC9qqxSwSKgRJeZ9wygIaehbHFHFhcBaMDKpiZlBHyz
rsnnlFXCb5s8HKn5LsUgGvB24L7sGNZP2CX7dhHov+YhD+jozLW2p9W4959Bz2Ei
RmqDtmiXLnzqTpXbI+suyCsohKRg6Un0RC47+cpiVwHiXZAW+cn8eiNIjqbVgXLx
KPpdzvvtTnOPlC7SQZSYmdunr3Bf9b77AiC/ZidstK36dRILKz7OA54=
-----END CERTIFICATE-----
)literal";
// Optional: Add client certificate and key for mutual TLS if needed
// const char* clientCertKey = "";
// const char* clientCert = "";
NetworkClientSecure secureClient;
// const uint8_t* caCertBundle = (const uint8_t*) caCertBundlePEM;
// size_t caCertBundleSize = strlen(caCertBundlePEM);
void setup() {
Serial.begin(115200);
// Connect WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to WiFi");
//Serial.println(caCertBundleSize);
// Set the Root CA Certbundle
//secureClient.setCACertBundle(caCertBundle, caCertBundleSize);
secureClient.setCACert(caCertBundlePEM);
// Establish secure connection to server
if (secureClient.connect(host, port)) {
Serial.println("Connected to server");
// Create the POST data
String postData = "AvantMaker=HelloFromESP32";
// Send the POST request
secureClient.print("POST /post HTTP/1.1\r\n");
secureClient.print("Host: www.httpbin.org\r\n");
secureClient.print("Content-Type: application/x-www-form-urlencoded\r\n");
secureClient.print("Content-Length: ");
secureClient.print(postData.length());
secureClient.print("\r\nConnection: close\r\n\r\n");
secureClient.print(postData);
// Wait for server response
while (secureClient.connected() && !secureClient.available()) {
delay(10);
}
// Read response
if (secureClient.available()) {
String response = secureClient.readString();
Serial.print("Server response:\n");
Serial.println(response);
} else {
Serial.println("No data available");
}
secureClient.stop();
} else {
Serial.println("Failed to connect to server! Check the code description for solution.");
return;
}
//secureClient.setCACertBundle(caCertBundle, caCertBundleSize);
if (!secureClient.connect(host2, 443)) {
Serial.println("Connection failed. Check code description for solution.");
return;
}
Serial.println("Connected to server!");
secureClient.println("GET /a/check HTTP/1.1");
secureClient.println("Host: www.howsmyssl.com");
secureClient.println("Connection: close");
secureClient.println();
// Wait for server response
while (secureClient.connected()) {
String line = secureClient.readStringUntil('\n');
if (line == "\r") {
Serial.println("Headers received");
break;
}
}
// Check and read available data
while (secureClient.available()) {
char c = secureClient.read();
Serial.print(c);
}
secureClient.stop();
Serial.println("\nConnection closed");
}
void loop() {
}
Explanation:
This example demonstrates how to use the ESP32’s NetworkClientSecure
library to establish secure connections to two servers—www.httpbin.org
and www.howsmyssl.com
—using a single PEM-formatted Root CA certificate bundle. We’ll send a POST request to one server and a GET request to the other, all while keeping things secure with TLS. It’s a great starting point for IoT projects needing to talk to the web safely, like sending sensor data or fetching updates!
ESP32 Library Index
- ESP32 WiFi Library
- ESP32 WiFiClient Library
- ESP32 HTTPClient Library
- ESP32 WebServer Library
- ESP32 WiFiClientSecure Library
- Connection
- Data Sending
- Data Receiving
- Which ESP32 Boards are Recommended for Learners
- How to Copy Codes from AvantMaker.com
- What is SPIFFS and how to upload files to it?
- What is LIttleFS and how to upload files to it?
Ready to experiment and explore more about ESP32? Visit our website’s All About ESP32 Resources Hub, packed with tutorials, guides, and tools to inspire your maker journey. Experiment, explore, and elevate your skills with everything you need to master this powerful microcontroller platform!