Using certificates from the Windows certificate store


I recently had to setup some web services that used certificates to communicate back and forth and one thing I found is that pretty much every site I found references on was using a file on the file system to access the client certificate.  What we wanted to do was access the certificates directly from the store.  After a little playing around we got it to work, so I though I would put this out in case someone else wants to do the same.  There is another X509Certificate2Collection item at MSDN, however the one for the X509Certificate2 only shows getting the file.

Assuming:
using System.Security.Cryptography.X509Certificates;

private X509Certificate GetCertificate()
{
    X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
    store.Open(OpenFlags.ReadOnly);
    X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySerialNumber, "123456", true);
    store.Close();
    return certs[0];
}

There are several ways to do the search, I like the FindBySerialNumber, but you can also search by DN, SubjectName, etc. 

Comments (2)

  1. So I was faced with the problem of sending an encrypted email to a group of people. Not really thinking,

Skip to main content