Encrypting and signing Mail in .Net part 2/5 (retrieving certificats)
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.
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; <br> /// 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);<br> try { //NOTE FALSE IS ONLY USED FOR TESTS SHOULD BE CHANGED TO true<br> 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.
-
15/05/2011 at 18:57Encrypting and signing Mail in .Net part 3/5 (Building the content – with attachments) « iStern
-
15/05/2011 at 19:01Encrypting and signing Mail in .Net part 4/5 (Signing the content) « iStern
-
15/05/2011 at 19:32Encrypting and signing Mail in .Net part 5/5 (Encrypting the content and sending the mail) « iStern
-
15/05/2011 at 19:45Encrypting and signing Mail in .Net part 5/5 (Encrypting the content and sending the mail) « iStern Blog