是否有可能在 Xamarin 中为 Android 使用 TLS12 SslStream?

Is there any possibility to use TLS12 SslStream in Xamarin for Android?

我知道 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);

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

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 将是 preferred/secure 方式...

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中为release/debug添加:

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