Introduction
Security is a core part of any IoT application. In this episode, we’ll explore securing CoAP communication between two Thread nodes. We will use DTLS (Datagram Transport Layer Security) with Pre-Shared Keys (PSK). This ensures your data, like sensor readings or control messages, cannot be intercepted or tampered with.
Why DTLS?
DTLS is the UDP-compatible version of TLS (used in HTTPS). Since Thread uses UDP for communication (including CoAP), DTLS fits naturally to provide encryption, message integrity, and optional authentication.
Approach: DTLS with Pre-Shared Keys
We’ll configure both Thread devices to use a matching PSK. The DTLS session will be established before CoAP messages are exchanged.
Required Components
- STM32WB with OpenThread and MbedTLS enabled.
- CoAP over secure DTLS session.
- Matching PSK and identity on both nodes.
Setting Up DTLS on the Server (Device B)
Configure the DTLS context and bind it to a socket that listens for incoming secure connections:
static const uint8_t kPsk[] = "hardfault_secure_key";
static const char *kPskIdentity = "client1";
void SetupDtlsServer() {
otPlatDtlsPskSet(otInstance, kPskIdentity, kPsk, sizeof(kPsk));
otPlatDtlsListen(otInstance, DtlsReceiveHandler, NULL);
}
void DtlsReceiveHandler(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) {
// Process decrypted CoAP request
HandleLedRequest(aContext, aMessage, aMessageInfo);
}
Setting Up DTLS on the Client (Device A)
The client must also set the same PSK before initiating a CoAP request:
void SetupDtlsClient() {
otPlatDtlsPskSet(otInstance, "client1", (const uint8_t *)"hardfault_secure_key", strlen("hardfault_secure_key"));
}
void SendSecureCoapRequest() {
SetupDtlsClient();
// Initiate CoAP POST over DTLS
RequestTempData(&peerAddr); // Your existing CoAP function
}
Integration with CoAP
Once DTLS is set up and connected, CoAP messages are automatically encrypted and authenticated when sent over that connection.
Debugging Tips
- Ensure both PSK and identity match on both nodes.
- Use logging (e.g., UART or RTT) to confirm DTLS handshake success.
- Check for DTLS-related errors using
otErrorcodes.
Security Benefits
- Encryption of data in transit.
- Authentication using PSK to prevent spoofing.
- Message integrity validation to prevent tampering.
Conclusion
By adding DTLS with PSK, you’ve now secured CoAP-based communication between Thread nodes, enabling encrypted and trusted messaging. In the next episode, we’ll build on this. We will create a simple Thread-based sensor dashboard. It will use a border router and an MQTT bridge.

Leave a comment