有没有可能在Xamarin for Android中使用TLS12 SslStream?

时间:2016-11-11 20:02:59

标签: c# xamarin xamarin.android tls1.2 sslstream

我知道Mono在当前版本的Xamarin中不支持TLS1.1和TLS1.2所以也许有可能在我的路上实现TLS12?

这部分代码不适用于Xamarin.Android:

_clientSocket = new TcpClient();
await _clientSocket.ConnectAsync(host, port);
_stream = new SslStream(_clientSocket.GetStream(), false);
_stream.AuthenticateAsClient(host, null, SslProtocols.Tls12, false);

1 个答案:

答案 0 :(得分:1)

确保将SSL / TLS实施设置为Native TLS 1.2+  因此使用BoringSsl与Mono的托管TLS相比。如果使用托管实现,则您的客户端将仅协商1.1。

enter image description here

var _clientSocket = new TcpClient();
using (var _stream = new SslStream(_clientSocket.GetStream(), false, new RemoteCertificateValidationCallback(CertificateValidation)))
{
    await _stream.AuthenticateAsClientAsync(host, null, SslProtocols.Tls12, false);
    // do something with your stream

    // FYI: Bug/Issue with Xamarin.Android, the following always return `None`
    Log.Debug(TAG, $"CipherAlgorithm: {_stream.CipherAlgorithm.ToString()}");
    Log.Debug(TAG, $"KeyExchangeAlgorithm: {_stream.KeyExchangeAlgorithm.ToString()}");
    Log.Debug(TAG, $"HashAlgorithm: {_stream.HashAlgorithm.ToString()}");

    // The following are not implemented in Xamarin Mobile, tagged as "Need to Implement"
    // Mobile CipherStrength = NotImplementedException
    // Mobile KeyExchangeStrength = NotImplementedException
    // Mobile HashStrength = NotImplementedException

}
  • 处理RemoteCertificateChainErrors

为了处理自签名证书上的RemoteCertificateChainErrors,您可以提供自定义RemoteCertificateValidationCallback,而只需提供true,您应该检查是否正确提供了server / cert,但将其添加到TrustManager将是首选/安全的方式...

static bool CertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors certificateErrors)
{
    Console.WriteLine("CertificateValidation");
    Console.WriteLine(certificate.ToString(true));
    Console.WriteLine("Chain");
    Console.WriteLine(chain);
    Console.WriteLine("\tError(s)");
    Console.WriteLine(certificateErrors);
    Console.WriteLine();
    return true;
}

更新

通过.csproj(或xbuild/msbuild)进行手动设置,在PropertyGroup内进行发布/调试,您可以添加:

<AndroidHttpClientHandlerType>Xamarin.Android.Net.AndroidClientHandler</AndroidHttpClientHandlerType>
<AndroidTlsProvider>btls</AndroidTlsProvider>