Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

xamarin.android adding client certificate

I'm trying to send a request to a web api in Xamarin.Android. The api requires a client certificate. I followed the advice in this question: xamarin.ios httpclient clientcertificate not working with https, but I get a "method not implemented" exception. Can anyone help?

Here's my code:

    string result = await CallApi(new System.Uri("myurl"));

    protected async Task<string> CallApi(Uri url)
    {
        try
        {
            AndroidClientHandler clientHandler = new AndroidClientHandler();
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3;

            using (var mmstream = new MemoryStream())
            {
                Application.Context.Assets.Open("mycert.pfx").CopyTo(mmstream);
                byte[] b = mmstream.ToArray();

                X509Certificate2 cert = new X509Certificate2(b, "password", X509KeyStorageFlags.DefaultKeySet);
                clientHandler.ClientCertificates.Add(cert);
            }

            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return true; });

            HttpClient client = new HttpClient(clientHandler);
            HttpResponseMessage response = await client.GetAsync(url);
            response.EnsureSuccessStatusCode();

            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
            return responseBody;
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("
Exception Caught!");
            return string.Empty;
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In the post you mentioned probably the managed handler is used. Since this handler currently doesn't support TLS 1.2 you shouldn't use it, but instead really use the AndroidClientHandler (see also Xamarin and TLS 1.2). Unfortunately ClientCertificates is indeed not implemented in AndroidClientHandler.

If you want to use client certificate with android you can extend the AndroidClientHandler:

using Java.Security;
using Java.Security.Cert;
using Javax.Net.Ssl;
using Xamarin.Android.Net; 
using Xamarin.Forms;

public class AndroidHttpsClientHandler : AndroidClientHandler
{
    private SSLContext sslContext;

    public AndroidHttpsClientHandler(byte[] customCA, byte[] keystoreRaw) : base()
    {
        IKeyManager[] keyManagers = null;
        ITrustManager[] trustManagers = null;

        // client certificate
        if (keystoreRaw != null)
        {
            using (MemoryStream memoryStream = new MemoryStream(keystoreRaw))
            {
                KeyStore keyStore = KeyStore.GetInstance("pkcs12");
                keyStore.Load(memoryStream, clientCertPassword.ToCharArray());
                KeyManagerFactory kmf = KeyManagerFactory.GetInstance("x509");
                kmf.Init(keyStore, clientCertPassword.ToCharArray());
                keyManagers = kmf.GetKeyManagers();
            }
        }

        // custom truststore if you have your own ca
        if (customCA != null)
        {
            CertificateFactory certFactory = CertificateFactory.GetInstance("X.509");

            using (MemoryStream memoryStream = new MemoryStream(customCA))
            {
                KeyStore keyStore = KeyStore.GetInstance("pkcs12");
                keyStore.Load(null, null);
                keyStore.SetCertificateEntry("MyCA", certFactory.GenerateCertificate(memoryStream));
                TrustManagerFactory tmf = TrustManagerFactory.GetInstance("x509");
                tmf.Init(keyStore);
                trustManagers = tmf.GetTrustManagers();
            }
        }
        sslContext = SSLContext.GetInstance("TLS");
        sslContext.Init(keyManagers, trustManagers, null);
    }

    protected override SSLSocketFactory ConfigureCustomSSLSocketFactory(HttpsURLConnection connection)
    {
        SSLSocketFactory socketFactory = sslContext.SocketFactory;
        if (connection != null)
        {
            connection.SSLSocketFactory = socketFactory;
        }
        return socketFactory;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...