Search code examples
c#xamarintls1.2.net-standardsslstream

Xamarin iOS SslStream.AuthenticateAsUser() returns exception "Unknown Secure Transport error `PeerHandshakeFail'."


I'm working on a Xamarin application where i'm establishing a connection with a Server. The server code is currently a blackbox for me, i only have the documentation.

However, since the server switched to TLS1.2 i'm trying use .NET's SslStream to authenticate on my app. I made sure that both are using the same certificate. The certificate is selfsigned though.

Whenever i try to do AuthenticateAsClient i get the following exception:

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

Here's some part of my code:

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);
   }
}

(The ValidateServerCertificate always returns true)

Here's my method to get the certificate:

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;
}

Thanks in advance!


Solution

  • Here is a Warning in document about TLS1.2 in Xamarin IOS.May be helpful for you.

    the downside is that it requires the event loop to be running for async operations to be executed.

    SslStream.AuthenticateAsClientAsync Method : Authenticate the client side of a client-server connection as an asynchronous operation.

    So from your testing with async method ,this is the right solution. Glad solved it.