C#m2mqtt使用根CA,密钥和证书连接到AWS代理

时间:2017-03-27 20:35:33

标签: c# amazon-web-services certificate mqtt broker

我正在尝试使用M2MQtt库使用根CA,客户端证书和密钥连接到AWS MQTT代理。我使用以下C#客户端连接代码

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());

但是,这会因FormatException错误而失败。这可能与我不知道在哪里传递此连接的私钥有关。这是我已经使用AWSIoTPythonSDK在Python中进行原型设计的工作(见下文)

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')

有谁知道这应该如何运作?

1 个答案:

答案 0 :(得分:1)

我发现了我的问题。线索是,为了正确地对AWS进行身份验证,您需要提供证书(在我的情况下是PEM)以及私钥,我无法弄清楚如何传递到MqttClient()构造函数,因为它只拿一个“证书”。

解决方案是使用PFX / P12证书,其中包括PEM和私钥(谢谢你,微软,因为它不同)。有许多资源可以解释如何从PEM +密钥创建PFX(即here,此处,herehere等)。然后你必须使用X509Certificate2()类来引入PFX文件('2'是

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());