13. januar 2010 by Thomas Stern
Part two in the series of 5 on howto c# encrypt and sign
mail
So in this post we will looking at howto fetch the security
certs we installed in the last post. There are a few attributes you
can use for this, but for now i'm gonna settle with the serial
number for the certificate.
Link to post
1
The serial number can be found on the certificate it self so
open up mmc and add a snap in for the local computer, if you forgot
howto do this have a look in part 1 of series. Once you you found
your recently installed certificate double click the cert and
choose the fan details, click on serial number to allow you to see
the entire key.

Okay now we got the serial number.
now we gonna fetch it out with through .Net
using System;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using System.Text;
/// Finds a certificates on Localmachines local store based on its serial number
///
/// The serial number of the certificate to retrieve
/// The requested certificate, or null if the certificate is not found
public X509Certificate2 FindCertificateFromSerial(string serialNumber)
{
//Sets up a new store to look for at certificat in.
X509Store localStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
localStore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
try
{
//NOTE FALSE IS ONLY USED FOR TESTS SHOULD BE CHANGED TO true
X509Certificate2Collection matches = localStore.Certificates.Find(
X509FindType.FindBySerialNumber,
serialNumber,
false);
if (matches.Count > 0)
{
return matches[0];
}
else
{
return null;
}
}
finally
{
localStore.Close();
}
}
Note the false parameter passed to Certificates.Find this should
be change to true on live system that certificate that has expired
or a like, would also be returned. Also note you need a referencens
to System.Security so you can use the
using System.Security.Cryptography.Pkcs;
There are other possible ways to find the certifcate but i leave
that to you find thefindtype that fits your purpose best.