IoT ESP32 using ssl/tls certificate to connect width MQTT Broker (Part 2 )
If you want to follow from the beginning check this link (Part 1)
Overview
This article shows how to use MQTT communication under ssl/tls protocol with the ESP32 to publish encrypted messages and subscribe to topics .
We’ll use the Mosquitto broker installed on the same Raspberry Pi 3. The broker is responsible for receiving all messages, filtering the messages, decide who is interested in them and publishing the messages to all subscribed clients.
Prerequisites
- You should be familiar with the Raspberry Pi — read Getting Started with Raspberry Pi and Arduino IDE.
- You should have the Raspbian operating system installed in your Raspberry Pi — watch this youtube video for installing Raspbian Lite, Enabling and Connecting with SSH.
- You need esp32 controller
- Learn what’s MQTT and how it works.
Here’s the full code:
#include "WiFiClientSecure.h"
#include <PubSubClient.h>
#include "credentials.h"
// WiFi credentials
const char* ssid = "<name of your wifi router>";
const char* password = "<wifi password>";
// MQTT Broker credentials
const char* mqtt_broker = "<IP ADRESS OF THE BROKER>";
const char* topic = "test";
const int mqtt_port = 8883 ;
// Set ssl certificate
const char* root_ca = CA_CRT;
const char* server_cert = SERVER_CERT;
const char* server_key = SERVER_KEY;
// WiFiClient espClient;
WiFiClientSecure espClient;
PubSubClient client(espClient);
void setup() {
// Set software serial baud to 115200;
Serial.begin(115200);
// Connecting to a WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
//Connecting to a mqtt broker width ssl certification
espClient.setCACert(root_ca);
espClient.setCertificate(server_cert); // for client verification
espClient.setPrivateKey(server_key); // for client verification
// Connect to the MQTT Broker remotely
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
String client_id = "esp32-client";
client_id += String(WiFi.macAddress());
// Print the Name and the id of the esp32 controller
Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
if (client.connect( client_id.c_str())) {
Serial.println("Public emqx mqtt broker connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
// Publish and Subscribe
client.publish(topic, "Hi I'm ESP32 ^^");
client.subscribe(topic);
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
void loop() {
client.loop();
client.publish(topic, "message sent from the esp32 to MQTT BROKER encrypted");
// Send a message every 10 seconds
delay(10000);
}
in view to set your ssl certificates you need to create a credentials.h
At the end it should look like that :
#define CA_CRT \
"-----BEGIN CERTIFICATE-----\n" \
"MIIDVzCCAj+gAwIBAgIUIwOnfZCxwCKrQXHpbI0rVksEcaMwDQYJKoZIhvcNAQEL\n" \
"BQAwOzELMAkGA1UEBhMCSU4xDDAKBgNVBAoMA0lPVDEPMA0GA1UECwwGY2xpZW50\n" \
"MQ0wCwYDVQQDDAR0ZXN0MB4XDTIzMDMyMjEzNDIwNFoXDTI4MDMyODEzNDIwNFow\n" \
"OzELMAkGA1UEBhMCSU4xDDAKBgNVBAoMA0lPVDEPMA0GA1UECwwGY2xpZW50MQ0w\n" \
"CwYDVQQDDAR0ZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw019\n" \
"nD5LRamjn/QJR2J3XR4M8s01os6XyCtMsDHzSTn2U4RZEker2Irn3b7DBHYMiwql\n" \
"nDyulhs0Xz7y1a1tjnmN2aUBPrwcXx16ecEAVzbkb5QF0SONf1xHFOILIhyNRm8u\n" \
"tuiymt6/5muJABenn5d34yI3Cu+2Mei5RJLB4e3v/574VD5JpxrGl2bJaszQR5ID\n" \
"mgRvEP/sPnvDPnRrtaUaQncyU37E2XLpiZAb2IxDBsUCSNtlGBCMwFd4PSMmsI1p\n" \
"3IdLyPFNd8wGggowSTet2yrOiOBr8tYdsPacW7iEJ6BzImwrlMj52vrKh5qBI7/i\n" \
"E9K55B2YcCU6lfj5AQIDAQABo1MwUTAdBgNVHQ4EFgQU2Ivc8jRwORUEhX2rtd7v\n" \
"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Bpue3D3RVE+1y6X4n1yGYhhUDzuBKn7UHccFCB0eFddXWbfNLZawRkEwNj+\n" \
"He7WKOSZAoGAK8WeUTU4G+hCK0WH8p3/5Ly3md//16q4jwIi/jQJDlSzVEngERVe\n" \
"te+JLM+a5bj5AUMBhIpiN3HvTDJBI+wHqFpQhVJgTSnvxqVzGHV88syWftOZDO1I\n" \
"ujUkloyiTRuPMjbXlzXMf/e3PTJVL7sZcroYz+K0Hts0q2RT8Y3Hw1c=\n" \
"-----END RSA PRIVATE KEY-----\n"
And then you can import your credential.h file to your main file in view to upload it.
At the end you should see on your mqtt broker the following messages that will appear
Wrapping Up
In summary, I’ve shown the full basics concept of homemade IOT system width the broker part and the controller part .