MQTTnet使用TLS双向认证

MQTTnet使用TLS双向认证

关键代码,客户端证书同时需要证书和密钥,所以需要使用pfx类型证书。
pfx类型证书同时包含crt+key.

生成证书的脚本

openssl pkcs12 -export -in client.crt -inkey client.key -out client.pfx -passout pass:client
using MQTTnet;
using MQTTnet.Client.Options;
using MQTTnet.Formatter;
using System;
using System.Collections.Generic;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var factory = new MqttFactory();
            var mqttClient = factory.CreateMqttClient();
            var caCert = X509Certificate.CreateFromCertFile(@"certs/ca.crt");
            caCert = new X509Certificate(caCert.Export(X509ContentType.Cert));
            var clientCert = new X509Certificate2(@"certs/client.pfx", "client");
            var newCert = new X509Certificate2(clientCert.Export(X509ContentType.SerializedCert));
            Console.WriteLine(clientCert.ToString());
            Console.WriteLine(clientCert.HasPrivateKey);
            var options = new MqttClientOptionsBuilder()
                .WithClientId("cubic&bvemp4drrkplpi4tbfp0")
                .WithTcpServer("iot.cloudstone-iot.com", 31884)
                .WithTls(new MqttClientOptionsBuilderTlsParameters
                {
                    UseTls = true,
                    AllowUntrustedCertificates = true,
                    IgnoreCertificateChainErrors = true,
                    IgnoreCertificateRevocationErrors = true,
                    SslProtocol = SslProtocols.Tls,
                    CertificateValidationHandler = (o) =>
                    {
                        return true;
                    },
                    Certificates = new List<X509Certificate>(){
                        caCert,
                        newCert,
                    },
                })
                .WithCleanSession()
                .WithProtocolVersion(MqttProtocolVersion.V311)
                .Build();

            await mqttClient.ConnectAsync(options, CancellationToken.None);
        }
    }
}

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

×

喜欢就点赞,疼爱就打赏