You Want Electronic Components for your project. 

For more information, contact us at: 

Apply Encryption and Secure Communication Protocols


Encryption is the most important single technical security measure for IoT. It protects data in transit (device to cloud) and at rest. This lesson covers how TLS works, implementing it on ESP32 for MQTT and HTTPS, and setting up a Mosquitto broker with TLS.

How TLS Works — The Handshake

TLS provides three guarantees: encryption (confidentiality), authentication (verify server identity), and integrity (detect tampering in transit).

Step What happens Note
Step 1: Client Hello ESP32 sends: supported TLS version, cipher suites, and a random number. Negotiation begins
Step 2: Server Hello Broker responds with chosen cipher suite and sends its TLS certificate (public key signed by a CA). Server presents credentials
Step 3: Certificate verify ESP32 checks the broker certificate is valid, not expired, and signed by a trusted CA. If invalid: connection rejected. Client verifies server identity
Step 4: Key exchange Both parties use asymmetric cryptography to agree on a symmetric session key without transmitting it. Secure key agreement
Step 5: Encrypted session All subsequent data is encrypted with the session key. Eavesdroppers see only ciphertext. Secure communication established
ANALOGY
The TLS handshake is like a first meeting: (1) I want to talk privately. (2) They show their ID (certificate). (3) You verify the ID is real (signed by a trusted authority). (4) You agree on a private code without saying it aloud. (5) All future conversation uses that code.

TLS on ESP32 — MQTT over TLS (Port 8883)

C/C++ — ESP32 MQTT over TLS using WiFiClientSecure
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>

// Root CA certificate for your MQTT broker — embedded in firmware
const char* CA_CERT = "-----BEGIN CERTIFICATE-----\n"
                      "MIIDSzCCAjOgAwIBAgIUYour...CertHere...=\n"
                      "-----END CERTIFICATE-----\n";

const char* MQTT_HOST = "mqtt.yourdomain.com";
const int   MQTT_PORT = 8883;   // TLS port — always use 8883
const char* MQTT_USER = "your_access_token";
const char* MQTT_PASS = "";

WiFiClientSecure tlsClient;
PubSubClient     mqtt(tlsClient);

void setup() {
  WiFi.begin("SSID", "password");
  while (WiFi.status() != WL_CONNECTED) delay(500);

  // Set CA certificate to validate the broker identity
  tlsClient.setCACert(CA_CERT);

  // TESTING ONLY — disables ALL certificate verification!
  // tlsClient.setInsecure();  // ⚠ NEVER use in production!

  mqtt.setServer(MQTT_HOST, MQTT_PORT);
  if (mqtt.connect("esp32-secure-01", MQTT_USER, MQTT_PASS)) {
    Serial.println("Connected via TLS!");
    mqtt.publish("v1/devices/me/telemetry", "{\"temp\": 25.0}");
  } else {
    Serial.print("TLS failed: "); Serial.println(mqtt.state());
  }
}

CRITICAL
tlsClient.setInsecure() disables ALL certificate verification — it trusts any certificate from anyone. This removes all TLS protection against man-in-the-middle attacks. Always use setCACert() with the actual CA certificate. setInsecure() is ONLY acceptable for local development testing, never for production.

HTTPS on ESP32 — Secure HTTP Requests

C/C++ — HTTPS POST with certificate verification
#include <WiFiClientSecure.h>
#include <HTTPClient.h>

const char* CA_CERT = "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----\n";

void sendSecureHTTP(float temp, float hum) {
  WiFiClientSecure client;
  client.setCACert(CA_CERT);

  HTTPClient https;
  https.begin(client, "https://api.thingspeak.com/update");
  https.addHeader("Content-Type", "application/x-www-form-urlencoded");

  String body = "api_key=YOUR_KEY&field1=" + String(temp, 1) +
                "&field2=" + String(hum, 1);
  int code = https.POST(body);
  Serial.print("HTTPS response: "); Serial.println(code);
  https.end();
}

Setting Up Mosquitto with TLS — OpenSSL 6-Step Process

Generating TLS Certificates with OpenSSL
# Step 1: Generate Certificate Authority (CA) private key
openssl genrsa -out ca.key 2048

# Step 2: Generate self-signed CA certificate (10 years)
openssl req -new -x509 -days 3650 -key ca.key -out ca.crt \
  -subj "/CN=MyIoT-CA/O=NEDU-Rwanda/C=RW"

# Step 3: Generate broker private key
openssl genrsa -out broker.key 2048

# Step 4: Generate broker Certificate Signing Request (CSR)
openssl req -new -key broker.key -out broker.csr \
  -subj "/CN=mqtt.yourdomain.com/O=NEDU-Rwanda/C=RW"

# Step 5: Sign the broker certificate with the CA
openssl x509 -req -days 3650 -in broker.csr -CA ca.crt \
  -CAkey ca.key -CAcreateserial -out broker.crt

# Step 6: Configure Mosquitto TLS (/etc/mosquitto/conf.d/tls.conf)
listener 8883
cafile   /etc/mosquitto/certs/ca.crt
certfile /etc/mosquitto/certs/broker.crt
keyfile  /etc/mosquitto/certs/broker.key
require_certificate false  # Set to true for mutual TLS

# Embed ca.crt content in ESP32 firmware as CA_CERT string

NOTE
Self-signed certificates are fine for private deployments where you control both broker and all client devices. For public-facing brokers, use Let’s Encrypt (free trusted CA). The broker CN in the certificate MUST match the hostname the ESP32 uses to connect.

Certificate Fingerprint Pinning

Certificate pinning adds an extra layer: the device only accepts a specific known certificate identified by its SHA-256 fingerprint. This prevents attacks even if a CA is compromised.

C/C++ — Certificate Fingerprint Pinning
// Get fingerprint: openssl x509 -noout -fingerprint -sha256 -in broker.crt
const char* CERT_FINGERPRINT =
  "AA:BB:CC:DD:EE:FF:11:22:33:44:55:66:77:88:99:00"
  ":AA:BB:CC:DD:11:22:33:44:55:66:77:88:99:00:AA:BB";

WiFiClientSecure client;
void setup() {
  client.setFingerprint(CERT_FINGERPRINT);
  // Update fingerprint in firmware (via OTA) when cert is renewed
}

Check Your Understanding — Lesson 8.2

?
1. An ESP32 connects to a ThingsBoard MQTT broker using WiFiClientSecure with setInsecure(). The connection works and data appears on the dashboard. Why is this NOT acceptable for hospital patient monitoring even though it ‘works’?
?
2. Explain in your own words what the TLS handshake achieves. Why must the broker’s certificate be validated? What specific attack does this prevent?
?
3. A Mosquitto broker is configured with TLS on port 8883. An ESP32 fails with ‘Certificate validation failed’. List THREE possible causes and the diagnostic step for each.

I'm an Embedded & AIoT Systems Engineer and the Founder & CEO of Nyereka Tech, a Rwanda-based startup enabling access to STEM tools, training, and innovation. I'm passionate about empowering young innovators through practical technology education and local manufacturing solutions.