M2Mqtt使用TLS双向认证

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;

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 wind.kaisa@gmail.com

×

喜欢就点赞,疼爱就打赏