【问题标题】:Xamarin iOS SslStream.AuthenticateAsUser() returns exception "Unknown Secure Transport error `PeerHandshakeFail'."Xamarin iOS SslStream.AuthenticateAsUser() 返回异常“未知安全传输错误‘PeerHandshakeFail’。”
【发布时间】:2019-07-09 15:21:13
【问题描述】:

我正在开发一个 Xamarin 应用程序,我正在与服务器建立连接。服务器代码目前对我来说是一个黑匣子,我只有文档。

但是,由于服务器切换到 TLS1.2,我正在尝试使用 .NET 的 SslStream 在我的应用程序上进行身份验证。我确保两者都使用相同的证书。 证书是自签名的

每当我尝试执行 AuthenticateAsClient 时,都会出现以下异常:

Mono.Security.Interface.TlsException: Unknown Secure Transport error `PeerHandshakeFail'.

这是我的代码的一部分:

using (var stream = new SslStream(new NetworkStream(mainSocket), false, new RemoteCertificateValidationCallback(ValidateServerCertificate)))
{
   try
   {
       stream.AuthenticateAsClient(ServerIpAdressServer, GetX509CertificateCollection(), System.Security.Authentication.SslProtocols.Tls12, false);
   }
   catch (Exception e)
   {
       Console.WriteLine(e);
   }
}

(ValidateServerCertificate 总是返回 true)

这是我获得证书的方法:

public static X509CertificateCollection GetX509CertificateCollection()
{
    var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MyClass)).Assembly;
    X509CertificateCollection collection1;
    using (MemoryStream ms = new MemoryStream())
    {
        assembly.GetManifestResourceStream("namespace.cert.pem").CopyTo(ms);
        X509Certificate2 certificate1 = new X509Certificate2(ms.ToArray());
        collection1 = new X509CertificateCollection();
        collection1.Add(certificate1);
    }
    return collection1;
}

提前致谢!

【问题讨论】:

  • 可能客户端与TLS1.2中的服务器不兼容。
  • @JuniorJiang-MSFT 你知道有什么原因吗?通常xamarin iOS应该兼容TLS1.2吧?
  • 好吧,我已经分享了答案。

标签: c# xamarin tls1.2 .net-standard sslstream


【解决方案1】:

这是document 中关于 Xamarin IOS 中 TLS1.2 的警告。可能对您有所帮助。

缺点是它需要运行事件循环才能执行异步操作。

SslStream.AuthenticateAsClientAsync Method :将客户端-服务器连接的客户端身份验证为异步操作。

所以从您使用异步方法的测试来看,这是正确的解决方案。很高兴解决了。

【讨论】:

  • 感谢您迄今为止的帮助!我的项目正在最新版本的 Xamarin.iOS 和 Forms 上运行。我还将 HttpClient 实现设置为NSUrlSession。但我意识到,在文章中它说,TLS1.2 的缺点是操作需要异步操作。所以如果我使用 TLS1.2,也许我需要使用AuthenticateAsClientAsync()
  • @EliasJohannes 你可以试试 AuthenticateAsClientAsync 。如果不起作用,请尝试以下操作:在“项目选项 > iOS 构建”下,将“SSL/TLS 实施”设置更改回旧的默认设置“Mono (TLS v1.0)”。如果有帮助,感谢您提前标记。
  • 我真的通过使用异步身份验证方法让它工作了。您的链接使我走上了正确的道路。如果您愿意,您可以编辑您的答案,以便我将其标记为已接受
  • @EliasJohannes Okey,很高兴这有效。我已经更新了答案,感谢您提前回复和标记:)
猜你喜欢
  • 1970-01-01
  • 2014-07-22
  • 2016-08-05
  • 2016-01-28
  • 2017-01-13
  • 2015-05-11
  • 2019-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多