C#: A useful certificate helper class

Hackered
Monday, January 26, 2015
by Sean McAlinden

Here is a little certificate helper class I regularly use, I'm putting online mainly to save me scouring old projects each time I need it.

It is basically a helper for finding X509 certificates by thumbprint using c# (X509Certificate2).

I have also included a method for loading an X509 certificate from the file system and a little factory method for creating X509SigningCredentials.

public static class CertificateHelper
{
    public static X509Certificate2 FindByThumbprint(string thumbprint, StoreName storeName, StoreLocation storeLocation)
    {
        var certificateStore = new X509Store(storeName, storeLocation);
        certificateStore.Open(OpenFlags.ReadOnly);

        foreach (var certificate in certificateStore.Certificates)
        {
            if (certificate == null || certificate.Thumbprint == null)
            {
                continue;
            }

            if (string.Equals(certificate.Thumbprint, thumbprint, StringComparison.InvariantCultureIgnoreCase))
            {
                certificateStore.Close();
                return certificate;
            }
        }

        throw new ArgumentException(string.Format("Cannot find certificate with thumbprint {0} in certificate store: {1} at location: {2} ", thumbprint, storeName, storeLocation));
    }

    public static X509Certificate2 FindFromFile(string certificatePath, string password)
    {
        var x509Certificate2 = new X509Certificate2();

        x509Certificate2.Import(certificatePath, password, X509KeyStorageFlags.DefaultKeySet);

        return x509Certificate2;
    }

    public static X509SigningCredentials CreateSigningCredentials(X509Certificate2 certificate)
    {
        return new X509SigningCredentials(certificate);
    }
}

In case you need it, here is a link which will show you how to create a signing certificate: http://www.hackered.co.uk/articles/create-signing-certificate-jwt-token