为MQTTnet客户端消息的TLS / SSL加密导入的PFX证书可与服务一起使用,但与Xamarin UWP App无关

如何解决为MQTTnet客户端消息的TLS / SSL加密导入的PFX证书可与服务一起使用,但与Xamarin UWP App无关

我们正在尝试做的事情

我们正在加密MQTT消息。我们一直在使用MQTTnet。这支持TLS加密,因此这是为现有解决方案启用此功能的问题。我们的UWP Xamarin应用程序和.NET控制台应用程序对所有MQTT都使用相同的.NET标准DLL。对于代理,我们使用的是Mosquitto,但我们计划切换到使用MQTTnet服务器的简单应用程序。

问题出在这里

我们已经在代理端以及一个控制台应用程序中成功添加了TLS加密,但是在使用UWP Xamarin应用程序时遇到了麻烦。在当前状态下,它会引发异常,并显示消息“提供的客户端证书缺少必需的私钥信息。”

我们在寻找什么

  • 确认这是可能的
  • 对为什么此方法不起作用的基本理解(即,确认我们的假设或其他假设)
  • 此问题的解决方案
  • 要检查的事物的想法。

因此,如果有人知道“答案”,那就太好了。否则,会有想法,建议,专业知识,分享的经验等。

我们的假设

  • 我们假设这是可能的
  • 这似乎不是MQTTnet错误或限制
  • 我们假设使用Xamarin UWP应用程序时出现此错误的原因是由于对磁盘访问或注册表访问的某些限制
  • 我们一直认为,由于PFX文件可与控制台应用程序一起使用,因此它也应适用于Xamarin UWP应用程序(但我们一直在研究该文件所在的存储区,因为Xamarin UWP应用程序只能在以下位置访问该文件)用户密钥库)

我们尝试过的事情

  • 我们已经阅读了MSDN上的规范文档
  • 我们已经阅读了博客文章
  • 我们已阅读并遵循了各种Stack Overflow帖子中的建议
  • 我们已阅读并遵循了各种MQTTnet支持文章的建议
  • 我们尝试了两种不同的代理(Mosquitto和使用MQTTnet服务器的示例应用程序)。
  • 我们尝试使用OpenSSL创建证书,并通过操作系统(Windows 10)手动创建证书;为了获得更可控制/确定性/可重复的结果,我们将切换到使用PS脚本
  • 我们尝试为用户存储和计算机存储创建证书
  • 我们尝试将证书导入商店(请参见代码)
  • 我们为X509KeyStorage标志尝试了许多不同的组合(例如,可导出,持久,用户密钥集等)
  • 我们尝试以管理员身份运行Visual Studio
  • 我们已使用SysInternals ProcMon并尝试确定失败的地方(即HD访问或注册表访问)
  • 我们尝试为Xamarin应用程序启用不同的功能

有用链接

我们的某些代码

    /// <summary>
    /// Connect to the MQTT broker using the defined options
    /// </summary>
    private async Task ConnectAsync()
    {
        IMqttClientOptions options = CreateMqttClientOptions();
    
        try
        {
            await m_mqttClient.ConnectAsync(options);
        }
        catch (Exception ex)
        {
            m_logger?.LogCritical(ex,"Failed to reconnect - service unavailable");
        }
    }
    
    /// <summary>
    /// Helper function used to create the MQTT client options object. This includes the certificate.
    /// </summary>
    private IMqttClientOptions CreateMqttClientOptions()
    {
        string filepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"MobileTools.2.pfx");
    
        X509Certificate2 certificate = new X509Certificate2(
            filepath,"notactuallymypassword",X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserKeySet);
    
        //InstallCertificate(certificate);
    
        // Set-up options.
        return new MqttClientOptionsBuilder()
            .WithCleanSession(true)
            .WithClientId(m_clientID)
            .WithTcpServer("NotActuallyDnsName",m_configuration.Port)
            .WithTls(new MqttClientOptionsBuilderTlsParameters
            {
                Certificates = new List<byte[]>
                {
                    certificate.Export(X509ContentType.Cert)
                },CertificateValidationCallback = (X509Certificate xCertificate,X509Chain xChain,SslPolicyErrors sslPolicyErrors,IMqttClientOptions clientOptions) =>
                {
                    return true;
                },UseTls = true
            })
           .Build();
    }
    
    /// <summary>
    /// Helper function used to create the MQTT client options object. This includes the certificate.
    /// </summary>
    private void InstallCertificate(X509Certificate2 certificate)
    {
        X509Store store = new X509Store(StoreName.My,StoreLocation.CurrentUser);
    
        store.Open(OpenFlags.ReadWrite);
        store.Add(certificate);
        store.Close();
    }

堆栈跟踪

The client certificate provided is missing the required private key information. ---> System.ArgumentException: The parameter is incorrect.

The client certificate provided is missing the required private key information.
   at Windows.Networking.Sockets.StreamSocketControl.put_ClientCertificate(Certificate value)
   at MQTTnet.Implementations.MqttTcpChannel.ConnectAsync(CancellationToken cancellationToken)
   at MQTTnet.Internal.MqttTaskTimeout.WaitAsync(Func`2 action,TimeSpan timeout,CancellationToken cancellationToken)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout,CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at MQTTnet.Adapter.MqttChannelAdapter.WrapException(Exception exception)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout,CancellationToken cancellationToken)
   at MQTTnet.Client.MqttClient.ConnectAsync(IMqttClientOptions options,CancellationToken cancellationToken)
   at TS.Orbit.MQTTLib.Client.MqttNetClient.ConnectAsync(IMQTTClientConfiguration configuration)

解决方法

我遇到了几乎完全相同的问题,对我来说,解决方案是创建并实现一个自定义TLS参数类,该类扩展了基础MqttClientOptionsBuilderTlsParameters类并覆盖了Certificates属性。

public class CustomTLSParameters : MqttClientOptionsBuilderTlsParameters
    {
        public new IEnumerable<X509Certificate> Certificates { get; set; }
    }

因此客户最终成为:

var MQTTClient = new MqttFactory().CreateManagedMqttClient();
var url = "myIP";
var port = 8883;
var certs = new List<X509Certificate> {
       new X509Certificate2("myCert.pfx")
};
var tlsParams = new CustomTLSParameters () {
                    AllowUntrustedCertificates = true,UseTls = true,Certificates = certs,IgnoreCertificateChainErrors = true,IgnoreCertificateRevocationErrors = true
                };
var options = new ManagedMqttClientOptionsBuilder()
                    .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                    .WithClientOptions(new MqttClientOptionsBuilder()
                        .WithClientId(Guid.NewGuid().ToString())
                        .WithTcpServer(url,port)
                        .WithTls(tlsParams)
                        .WithCleanSession()
                        .Build())
                    .Build();

await MQTTClient.StartAsync(options);

我认为它与UWP的MqttClientOptionsBuilderTlsParameters类定义有关,我注意到它为Certificates属性定义了IEnumerable<IEnumerable<bytes>>而不是IEnumerable<X509Certificate>

*注意:MQTTnet v3.0.13

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-