1

I am trying to use M2MQtt library to connect to AWS MQTT broker using a root CA, client certificate and key. I am using the following C# client connection code

MqttClient client = new MqttClient(
    endPoint, 
    MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT,
    true,
    new X509Certificate2(@"ca.pem"),
    new X509Certificate2(@"certificate.pem"),
    MqttSslProtocols.TLSv1_2 
    );
client.Connect(Guid.NewGuid().ToString());

however, this fails with a FormatException error. It's probably related to the fact that I don't know where to pass in the private key for this connection. This is something that I already have working, prototyped in Python using AWSIoTPythonSDK (see below)

from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient

f = open('mqttEndpoint.txt', 'r')
awsHost = f.read()
f.close()

myAWSIoTMQTTClient = AWSIoTMQTTClient('foo')
myAWSIoTMQTTClient.configureEndpoint(awsHost, 8883)
myAWSIoTMQTTClient.configureCredentials('ca.pem', 'id_rsa', 'certificate.pem')

Does anyone know how this is supposed to work?

Paul Grinberg
  • 1,184
  • 14
  • 37

1 Answers1

1

I figured out my problem. The clue was the fact that to properly authenticate against AWS, you need to provide both the certificate (a PEM in my case) as well as the private key, which I could not figure out how to pass into MqttClient() constructor, because it takes only one "certificate".

The solution is to use a PFX/P12 certificate, which includes inside it both a PEM and a private key (thank you, Microsoft, for being different). There are many resources that explain how to create a PFX from a PEM+key (i.e. here, here, here, here, etc). Then you have to use a X509Certificate2() class to pull in the PFX file (that '2' is

MqttClient client = new MqttClient(
    endPoint,
    MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT,
    true,
    rootCa,
    new X509Certificate2(@"certificate.pfx", @""); // My PFX was created with a blank password, hence empty string as 2nd arg
    MqttSslProtocols.TLSv1_2
    );
client.Connect(Guid.NewGuid().ToString());
Community
  • 1
  • 1
Paul Grinberg
  • 1,184
  • 14
  • 37