Working with Certificates in Code

Just a quick little collection of useful code snippets when dealing with certificates.  Some of these don’t really need to be in their own methods but it helps for clarification.

Namespaces for Everything

using System.Security.Cryptography.X509Certificates;
using System.Security;

Save Certificate to Store

// Nothing fancy here.  Just a helper method to parse strings.
private StoreName parseStoreName(string name)
{
    return (StoreName)Enum.Parse(typeof(StoreName), name);
}
	
// Same here
private StoreLocation parseStoreLocation(string location)
{
    return (StoreLocation)Enum.Parse(typeof(StoreLocation), location);
}
	
private void saveCertToStore(X509Certificate2 x509Certificate2, StoreName storeName, StoreLocation storeLocation)
{
    X509Store store = new X509Store(storeName, storeLocation);

    store.Open(OpenFlags.ReadWrite);
    store.Add(x509Certificate2);

    store.Close();
}

Create Certificate from byte[] array

private X509Certificate2 CreateCertificateFromByteArray(byte[] certFile)
{
     return new X509Certificate2(certFile); 
	// will throw exception if certificate has private key
}

The comment says that it will throw an exception if the certificate has a private key because the private key has a password associated with it. If you don't pass the password as a parameter it will throw a System.Security.Cryptography.CryptographicException exception.

Get Certificate from Store by Thumbprint

private bool FindCertInStore(
    string thumbprint, 
    StoreName storeName, 
    StoreLocation storeLocation, 
    out X509Certificate2 theCert)
{
    theCert = null;
    X509Store store = new X509Store(storeName, storeLocation);

    try
    {
        store.Open(OpenFlags.ReadWrite);

        string thumbprintFixed = thumbprint.Replace(" ", "").ToUpperInvariant();

        foreach (var cert in store.Certificates)
        {
            if (cert.Thumbprint.ToUpperInvariant().Equals(thumbprintFixed))
            {
                theCert = cert;

                return true;
            }
        }

        return false;
    }
    finally
    {
        store.Close();
    }
}

Have fun!