/// <summary> /// Installs the certificate into the certificate store chosen. /// If the certificate is sucessfully installed, this will be recorded in the Persistant Storage /// </summary> /// <param name="cert">Certificate to install</param> /// <param name="storeName">The certificate store to use</param> /// <param name="storeLocation">The location within the certificate store to use</param> /// <returns>False if the user declined</returns> public static void InstallCertificate(X509Certificate2 cert, StoreName storeName, StoreLocation storeLocation) { _ = cert ?? throw new ArgumentNullException(paramName: nameof(cert)); if (IsCertificateInstalled(cert, storeName, storeLocation)) { return; } using var certStore = new X509Store(storeName, storeLocation); certStore.Open(OpenFlags.ReadWrite); Debug.WriteLine("Writing '{0}' to cert store {1}:{2}", cert.FriendlyName, storeName.ToString(), storeLocation.ToString()); try { // add to certificate store certStore.Add(cert); // ^ Will produce a popup prompt when installing to the root store // if the certificate is not already installed // There fore you should predict this // and warn+instruct the user } catch (CryptographicException ex) { // if user selects No when prompted to install the CA if ((uint)ex.HResult == 0x800704C7) { throw new UserAbortException("User selected No when prompted for certificate"); } Debug.WriteLine("THIS SHOULD NOT HAPPEN"); Debug.Print(ex.ToString()); Debug.Assert(false); throw; // unknown exception } // keep track of that we've installed it PersistingStore.InstalledCertificates = PersistingStore.InstalledCertificates .Add(InstalledCertificate.FromCertificate(cert, storeName, storeLocation)); }
public static bool IsCertificateInstalledByUs(X509Certificate2 cert, StoreName storeName, StoreLocation storeLocation) => IsCertificateInstalled(cert, storeName, storeLocation) && PersistingStore.InstalledCertificates .Contains(InstalledCertificate.FromCertificate(cert, storeName, storeLocation));