Xamarin.iOS => Create Key Pair and send public key (X.509) to ASP.NET MVC Application .NET 4.7.2

485 Views Asked by At

I'm new with RSA. I have made Windows and Xamarin.Android client application well communicate with ASP.NET MVC .NET 4.7.2 application. All is working. Client applications can share their public key with the server and server can made same thing with client applications.

Now I am implementing the solution in Xamarin.iOS and I followed this tutorial to create key pair : https://msicc.net/how-to-perform-asymmetric-encryption-without-user-input-hardcoded-values-with-xamarin-ios/

My problem is with exporting the public key to the server. The server is not recognize the public key.

There is my c# code that made exportation in Xamarin.iOS :

            var cert = this.publicKey.GetExternalRepresentation();
            var publicKeyBytes = new byte[cert.Length];
            System.Runtime.InteropServices.Marshal.Copy(cert.Bytes, publicKeyBytes, 0, Convert.ToInt32(cert.Length));
            return Convert.ToBase64String(publicKeyBytes, Base64FormattingOptions.InsertLineBreaks);

On server side, there is my c# code :

        var bytes = Convert.FromBase64String(cer);
        X509Certificate2 cert = new X509Certificate2(bytes);
        this.rsaDistant = cert.GetRSAPublicKey();

I spend long time checking posts and saw many examples in swift, objectif c. It seems that iOS didn't export to X.509 format. I also saw that Microsoft has made classes like SecCertificate and SecCertificate2 in Xamarin.iOS that can export X.509 certificate, but when I use it, debugger freeze at the export.

How can I achieve my goal ? Do you already made it with Xamarin.iOS ?

Thank you for your help !

1

There are 1 best solutions below

2
On

Did you check the apple docs : Storing a DER-Encoded X.509 Certificate ?

And here is a working sample using SecCertificate ,check the code below.

var path = Directory.GetParent(GlobaleObjekte.SSLZertifikatePath);
var caPath = Path.Combine(path.FullName, "ca.cert.der");
var caByteArray = File.ReadAllBytes(caPath);
var caCert = new SecCertificate(caByteArray);

var interPath = Path.Combine(path.FullName, "intermediate.cert.der");
var interByteArray = File.ReadAllBytes(interPath);
var interCert = new SecCertificate(interByteArray);

var clientPath = Path.Combine(path.FullName, "client.pfx");
var clientByteArray = File.ReadAllBytes(clientPath);
var clientCert = new X509Certificate2(clientByteArray, Settings.WSClientCertPasswort);

var identity = SecIdentity.Import(clientCert);
var credential = new NSUrlCredential(identity, new SecCertificate[] { caCert, interCert }, NSUrlCredentialPersistence.ForSession);

completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);