Validating the Certificate Chain


Ususally when tesitng with different certificates we usually need to check if the certificate chain is valid and this snippet came in quite handy in many places.


X509Certificate2 cert = FedUtil.LookupCertificate(StoreName.My, StoreLocation.LocalMachine, “CN=MyCertificate”);
X509Chain chain = new X509Chain
();
bool pass = chain.Build(cert);


Helper method to look up the certificate from the Store. I refactored this out of the WCF samples in the SDK.


 


public static X509Certificate2 LookupCertificate(StoreName storeName,


                                                           StoreLocation storeLocation,


                                                           string subjectDistinguishedName)


    {


        X509Store store = null;


        try


        {


            store = new X509Store(storeName, storeLocation);


            store.Open(OpenFlags.ReadOnly);


            X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName,


                                                                       subjectDistinguishedName, false);


            if (certs.Count != 1)


            {


                throw new Exception(“Certificate not found or more than one certificate found”);


            }


            return (X509Certificate2)certs[0];


        }


        finally


        {


            if (store != null) store.Close();


        }


    }


 

Comments (0)