Partager via


Capturing a PKI Certificate

I found it was easiest to use a certificate token when accessing systems using a certificate.  This is the method I use to accomplish the task querying based on the certificate thumbprint (the thumbprint ensures that I get correct certificate):

 public X509SecurityToken GetSecurityToken(string certThumb)
 {
 X509SecurityToken securityToken = null;
 X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
 store.Open(OpenFlags.ReadOnly);
 try
 {
 X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByThumbprint, certThumb, false);
 X509Certificate2 cert;
 if(certs.Count == 1)
 {
 cert = certs[0];
 securityToken = new X509SecurityToken(cert);
 }
 else
 {
 securityToken = null;
 }
 }
 catch (Exception)
 {
 throw;
 }
 finally
 {
 if(store != null)
 {
 store.Close();
 }
 }
 return securityToken;
 }