/// <summary> /// Lists the thumbprint value for each certificate in the specified store location which include "Key Encipherment" in its Key Usage extension /// </summary> /// <param name="Context">Store location from which to list certificate details (Either <see cref="X509Context.UserReadOnly"/> or <see cref="X509Context.SystemReadOnly"/>)</param> /// <param name="allowExpired">If set to True, expired certificates will be included in the output (Note that .NET will not perform cryptographic operations using a certificate which is not within its validity period)</param> /// <returns>A string expression listing all available certificate thumbprints and their expiration dates</returns> /// <example> /// <code> /// string availableCerts = <see cref="X509Utils"/>.<see cref="ListCerts"/>(<see cref="X509Context.UserReadOnly"/>); /// </code> /// </example> public static string ListCerts(X509Context Context = null, bool allowExpired = false) { if (Context == null) { Context = X509Context.UserReadOnly; } string output = "Key Encipherment Certificates found:\r\n\r\n"; bool firstAdded = false; X509Store store = new X509Store(Context.Location); store.Open(OpenFlags.ReadOnly); foreach (X509Certificate2 cert in store.Certificates) { if (X509CryptoAgent.IsUsable(cert, allowExpired)) { firstAdded = true; output += cert.Subject + "\t" + string.Format("Expires {0}", cert.NotAfter.ToShortDateString()) + "\t" + cert.Thumbprint + "\r\n"; } } if (!firstAdded) { output += "None.\r\n"; } return(output); }
/// <summary> /// Installs an encryption certificate and associated key pair in the specified X509Context /// </summary> /// <param name="infile">The PKCS#12 (usually with a .pfx or .p12 extension) containing the bundled certificate and key pair</param> /// <param name="PfxPassword">The password to unlock the PKCS#12 file</param> /// <param name="Context">The X509Context in which to place the certificate and key pair</param> /// <returns></returns> public static string InstallCert(string infile, SecureString PfxPassword, X509Context Context) { bool certInstalled = false; X509Certificate2Collection certCol = new X509Certificate2Collection(); X509Store keyChain; string thumbprint = string.Empty; try { certCol.Import(infile, PfxPassword.Plaintext(), X509KeyStorageFlags.PersistKeySet); keyChain = new X509Store(StoreName.My, Context.Location); keyChain.Open(OpenFlags.ReadWrite); foreach (X509Certificate2 cert in certCol) { if (X509CryptoAgent.IsUsable(cert, Constants.ProbeMode)) { keyChain.Add(cert); if (Context.Index == X509Context.Indexer.SystemFull || Context.Index == X509Context.Indexer.SystemReadOnly) { AddIISKeyAccess(cert.Thumbprint); } certInstalled = true; thumbprint = cert.Thumbprint; break; } } if (!certInstalled) { throw new X509CryptoException($"The PKCS#12 file {Path.GetFileName(infile).InQuotes()} did not contain a valid encryption certificate"); } else { return(thumbprint); } } finally { certCol = null; keyChain = null; } }