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

C# m2mqtt to connect to AWS broker using Root CA, key, and certificate

我正在尝试使用 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')

有人知道这是怎么回事吗?

我想通了我的问题。线索是为了正确地针对 AWS 进行身份验证,您需要同时提供证书(在我的例子中是 PEM)以及私钥,我无法弄清楚如何将其传递给 MqttClient() 构造函数,因为它只需要一个 "certificate".

解决方案是使用 PFX/P12 证书,其中包含 PEM 和私钥(感谢 Microsoft 与众不同)。有许多资源解释了如何从 PEM+密钥(即 here, here, here, here 等)创建 PFX。然后你必须使用 X509Certificate2() class 来拉入 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());