M2Mqtt使用TLS双向认证 - Sat, Dec 19, 2020
M2Mqtt使用TLS双向认证
关键代码,客户端同时需要证书和密钥,但是入参只有一个,所以需要使用pfx类型证书。 pfx类型证书同时包含crt+key.
生成证书的脚本
openssl pkcs12 -export -in client.crt -inkey client.key -out client.pfx -passout pass:client
证书的使用
var host = _config.AppSettings[Config.MqttHost];
var port = int.Parse(_config.AppSettings[Config.MqttPort]);
var caCert = new X509Certificate2(@"certs/ca.crt");
var temp = new X509Certificate2(@"certs/client.pfx", "client");
var clientCert = new X509Certificate(temp.Export(X509ContentType.SerializedCert));
// _client = new MqttClient(host, port, true, caCert, clientCert, MqttSslProtocols.TLSv1_0, new RemoteCertificateValidationCallback(UserCertificateValidationCallback), UserCertificateSelectionCallback)
_client = new MqttClient(host, port, true, caCert, clientCert, MqttSslProtocols.TLSv1_0, UserCertificateValidationCallback)
{
ProtocolVersion = MqttProtocolVersion.Version_3_1_1,
};
_client.MqttMsgPublishReceived += MqttMsgPublishEventHandler;
_client.ConnectionClosed += ConnectionClosedEventHandler;
_client.MqttMsgUnsubscribed += MqttMsgUnsubscribedEventHandler;
_client.MqttMsgSubscribed += MqttMsgSubscribedEventHandler;