对SSPI的调用失败,请参阅内部异常paho m2mqtt Dot.Net(c#)客户端SSL / TLS连接

时间:2017-05-16 05:23:48

标签: c# ssl mqtt mosquitto paho

我正在尝试通过SSL / TLS使用m2mqtt c#客户端版本4.3.0库连接mosquitto broker。以下是我试过的代码

static void Main(string[] args)
    {

        // create client instance
        MqttClient client = new MqttClient(IPAddress.Parse("127.0.0.1"), 8883, true, 
                                new X509Certificate2("C:\\Users\\hp\\Desktop\\certificate\\ca.crt"), 
                                new X509Certificate2("C:\\Users\\hp\\Desktop\\certificate\\client.crt"), 
                                MqttSslProtocols.TLSv1_2);

        // register to message received
        client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

        string clientId = "pahoSubscriber2";
        client.Connect(clientId);

        // subscribe to the topic "hello" with QoS 0
        client.Subscribe(new string[] { "hello" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });

    }

static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
    {
        // handle message received
        Console.WriteLine(e.Message);
    }

但我得到了例外

  
    

对SSPI的调用失败,请参阅内部异常。

  

内部异常说

  
    

收到的邮件意外或格式错误

  

有关信息,我可以成功连接没有SSL / TLS的代理。也可以通过使用或不使用SSL / TLS使用Paho Java客户端,我可以与代理连接。仅当我尝试通过SSL / TLS使用m2mqtt C#客户端库进行连接时才会发生此异常。任何帮助或示例实施都将得到满足。

1 个答案:

答案 0 :(得分:0)

终于找到了解决方案。要在Dot.Net框架内使用SSL证书,我们需要同时提供证书及其相应的私钥。为实现这一点,我们需要使用结合这两者的p12(.pfx)文件。在我的项目中,我使用OpenSSL使用自签名证书,所以我使用下面的命令来组合证书和私钥

pkcs12 -export -out ca.pfx -inkey ca.key -in ca.crt
pkcs12 -export -out client.pfx -inkey client.key -in client.crt

将为每个证书创建p12(.pfx)文件。然后我将它们用于我的代码,如下所示

static void Main(string[] args)
    {

        // create client instance
        MqttClient client = new MqttClient(IPAddress.Parse("127.0.0.1"), 8883, true, 
                                new X509Certificate2("C:\\Users\\hp\\Desktop\\certificate\\ca.pfx"), 
                                new X509Certificate2("C:\\Users\\hp\\Desktop\\certificate\\client.pfx"), 
                                MqttSslProtocols.TLSv1_2);

        // register to message received
        client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

        string clientId = "pahoSubscriber2";
        client.Connect(clientId);

        // subscribe to the topic "hello" with QoS 0
        client.Subscribe(new string[] { "hello" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });

    }

static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
    {
        // handle message received
        Console.WriteLine(e.Message);
    }