Thursday, July 31, 2014

Accessing the SSL Certificate with thumbprint rather than SignInCertificate Name

Use the below code to access the ssl certificate from its certificate store in Custom STS

public static X509Certificate2 GetCertificateByThumbprint(string thumbprint)
        {
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            X509Certificate2Collection certificates = null;
            store.Open(OpenFlags.ReadOnly);

            try
            {
                certificates = store.Certificates;

                var certs = certificates.Find(X509FindType.FindByThumbprint, thumbprint, false).OfType<X509Certificate2>().ToList();

                if (certs.Count == 0)
                    throw new ApplicationException(string.Format(Constants.ExceptionMessages.msgNocertificate, thumbprint));
                else if (certs.Count > 1)
                    throw new ApplicationException(string.Format(Constants.ExceptionMessages.msgMultipleCertificates, thumbprint));

                return new X509Certificate2(certs[0]);
            }
            finally
            {
                if (certificates != null)
                {
                    for (var i = 0; i < certificates.Count; i++)
                    {
                        var cert = certificates[i];
                        cert.Reset();
                    }
                }
                store.Close();
            }

        }


Note:- never copy and paste the thumbprint directly. Type the value in the web.config. While typing remove the white spaces.

No comments:

Post a Comment