Mycroft.Program.TryGetX509Certificate C# (CSharp) Method

TryGetX509Certificate() private static method

private static TryGetX509Certificate ( string args, X509Certificate2 &cert ) : bool
args string
cert System.Security.Cryptography.X509Certificates.X509Certificate2
return bool
        private static bool TryGetX509Certificate(string[] args, out X509Certificate2 cert)
        {
            var indexCertFlag = Array.IndexOf(args, "--cert");
            if (indexCertFlag >= 0)
            {
                // Make sure a certificate file was given
                var indexCertFile = indexCertFlag + 1;
                if (indexCertFile >= args.Length)
                {
                    Log.Error("--cert parameter must include certificate file");
                    cert = null;
                    return false;
                }

                // Load the certificate file
                var certFile = args[indexCertFile];
                try
                {
                    cert = new X509Certificate2(certFile);
                    return true;
                }
                catch (CryptographicException e)
                {
                    Log.Error(
                        String.Format(
                            "Failed to load certificate \"{0}\" - {1}",
                            certFile,
                            e.Message.Trim()
                        )
                    );
                    cert = null;
                    return false;
                }
            }

            // No file specified; load from certificate store
            // Accessing certificates may need to be abstracted for Mono
            X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
            Debug.WriteLine(store.Certificates.Count);

            var thumbprint = TlsServer.FormatCertificateThumbprint(
                ConfigurationManager.AppSettings["CertThumbprint"]
            );

            // Use the settings file to figure out which certificate to use
            var collection = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);

            // Make sure the desired fingerprint exists
            if (collection.Count == 0)
            {
                Log.Error(
                    String.Format(
                        "Error: Certificate with thumbprint {0} not found. Please make sure it is installed to the root CA store.",
                        thumbprint
                    )
                );
                cert = null;
                return false;
            }

            // Return the certificate
            cert = collection[0];
            return true;
        }