0

I'm basically new to mobile development and stuck for a few weeks because, I am unable to connect XAMARIN Android app with MQTTT over TLS.
Maybe i am using the wrong library or is it an Xamarin error?
My certificate is a .crt file from m21.cloudmqtt.com.

https://crt.sh/?id=5253106089

First was using System.Net MQTT but they are currently unable to work over TLS.
So i currently i am using MQTTNet, with (for the moment) the default certificate from m21.cloud.com which i have stored in Assets folder.
I tested this local with and without a certificate and its working fine. The MQTTNet Client with cert from local folder is like this, and works like it should:

var caCert = new X509Certificate2("C:/pathtocert.crt");
            var source = new CancellationTokenSource().Token;
            var token = source;

            var factory = new MqttFactory();
            var mqttClient = factory.CreateMqttClient();

            var mqttOptions = new MqttClientOptionsBuilder()
                .WithTcpServer(server, port)
                .WithClientId(clientId)
                .WithCredentials(username, pswd)
                .WithTls(new MqttClientOptionsBuilderTlsParameters
                {
                    UseTls = true,
                    Certificates = new List<X509Certificate> { caCert }
                })
                .Build();

            mqttClient.ConnectAsync(mqttOptions, token).Wait(token);

To get the Certifcate from Android Assets Folder i used the same client code as above and t et the certificate i used:

using (var assetStream = await Xamarin.Essentials.FileSystem.OpenAppPackageFileAsync("filename.crt"))
                using (var memStream = new MemoryStream())
                {
                    assetStream.CopyTo(memStream);
                    caCert = new X509Certificate(memStream.ToArray());
                }

I dont understand why its not working, for now its also okay if the certificate isn't used but it needs to use TLS. But tried, and i still get unauthorized error.

    var mqttOptions = new MqttClientOptionsBuilder()
                .WithTcpServer(server, port)
                .WithClientId(clientId)
                .WithCredentials(username, pswd)
                .WithTls(new MqttClientOptionsBuilderTlsParameters
                {
                    UseTls = true,
                })
                .Build();

Thanks in adnvance.

Pearl
  • 39
  • 7
  • have you verified that the certificate is loading properly when it is an Android Asset? And that it matches the cert you get when you load it from `C;`? – Jason Apr 14 '22 at 12:59
  • Yes also when using TLS without certificate i get the same error, or is it impossible to use mqttNet without certificate in android? – Pearl Apr 15 '22 at 10:42

0 Answers0