Azure IoT SDK for C – Secure Communication

Table of Contents Overview Prerequisites Project Setup TLS Configuration X.509 Certificate Authentication SAS Token Authentication Troubleshooting

Overview

This tutorial guides you through establishing a secure, encrypted connection between a C device application and Azure IoT Hub using the Azure IoT C SDK. You’ll learn how to configure TLS, use X.509 certificates, and generate SAS tokens.

Prerequisites

Project Setup

git clone https://github.com/Azure/azure-iot-sdk-c.git
cd azure-iot-sdk-c
mkdir cmake
cd cmake
cmake .. -Duse_prov_client=ON -Duse_amqp=ON -Duse_mqtt=ON -Duse_http=ON -Dskip_samples=ON
make

Ensure iothub_client_sample_mqtt builds successfully.

TLS Configuration

The SDK uses OpenSSL for TLS. Verify the OpenSSL version and configure the root CA bundle.

#define TRUSTED_CERTIFICATE_PATH "/etc/ssl/certs/ca-bundle.crt"

Pass the path during client creation:

IOTHUB_CLIENT_LL_HANDLE client = IoTHubClient_LL_CreateFromDeviceAuth(
    connectionString,
    MQTT_Protocol
);
IoTHubClient_LL_SetOption(client, OPTION_TRUSTED_CERT, TRUSTED_CERTIFICATE_PATH);

X.509 Certificate Authentication

Register a device with an X.509 certificate in IoT Hub, then use the private key and certificate files.

#define CERTIFICATE_PATH "/certs/device-cert.pem"
#define PRIVATE_KEY_PATH "/certs/device-key.pem"

IOTHUB_CLIENT_LL_HANDLE client = IoTHubClient_LL_CreateWithX509(cstrConnectionString,
                                                                MQTT_Protocol);
IoTHubClient_LL_SetOption(client, OPTION_X509_CERT, CERTIFICATE_PATH);
IoTHubClient_LL_SetOption(client, OPTION_X509_PRIVATE_KEY, PRIVATE_KEY_PATH);

SAS Token Authentication

If you prefer symmetric keys, generate a SAS token at runtime:

#include "azure_c_shared_utility/sastoken.h"

static char* generate_sas_token(const char* key, const char* hostname, const char* deviceId, uint32_t expiryInSec)
{
    char* token = NULL;
    const char* scope = hostname;
    const char* keyName = NULL; // optional
    token = SasToken_Create(key, keyName, scope, expiryInSec);
    return token;
}

Attach the token to the client:

char* sas = generate_sas_token(deviceKey, iothubHostname, deviceId, 3600);
IoTHubClient_LL_CreateFromConnectionString(sas, MQTT_Protocol);
free(sas);

Troubleshooting