[FIXED] Xamarin.Android Run SSL Server With Own Certificate

Issue

I’m working on Android devices that need to listen for incoming SSL connections over LAN, with a certificate installed on the client and the Android device. I’ve found threads like this that show how to connect as a client, but there doesn’t seem to be a server equivalent. I’m also needing to select one specific cert out of multiple installed on the device to use for serving SSL, and I’m not seeing how to do that specifically.

I had initially tried getting the cert as if it were on Windows, like:

X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        store.Open(OpenFlags.ReadOnly);
        X509Certificate2 cert;

        foreach (var item in store.Certificates)
        {
            if (item.SubjectName.Name.Contains("mycertname"))
            {
                cert = item;
                break;
            }
        }
        store.Close();
...
SslStream sslStream = new SslStream(
            client.GetStream(), false, new RemoteCertificateValidationCallback((a, b, c, d) => { return true; }));
            sslStream.AuthenticateAsServer(serverCertificate, clientCertificateRequired: true, checkCertificateRevocation: true);

but this doesn’t seem to be able to access any of the certs on the machine, even with different locations/names selected. I read that on Android you have to use the Java.Security.KeyStore, but I’m not finding a way to get a specific cert by name. Is there a more Java-like way that this needs to be run?

Edit: I’m realizing I can do something like

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

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

with the key just in the assets folder, but I’m really wanting a unique cert per device that’s not part of the apk. I’m not finding anything equivalent to this for finding certs that are installed on the device rather than part of the assets.

Solution

I’m realizing that the device will need to generate a CSR when it’s configured, so it can just save its own cert instead of installing one externally.

Answered By – eleviness

Answer Checked By – Cary Denson (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published