title: C# reading a certificate on Smart card
body: <p>I was looking for an advise on how to decrypt the emails using smart card. And I have posted a <a href="https://stackoverflow.com/questions/18189138/c-sharp-decrypt-emails-by-reading-keys-on-smart-card">query</a> here about the same. Mr Owlstead advised me to use the certificates to decrypt which normally available with smart card. Now I got struck at the point how would I be able to use the certificate to get the key and decrypt the emails. So I have tried the below code but I am getting Keyset not present exception. Can anybody help?</p>
  
  <pre><code>public static void DecryptContent(byte[] data)
          {
              X509Store st = new X509Store(StoreName.My, StoreLocation.CurrentUser);
              st.Open(OpenFlags.ReadOnly);
              X509Certificate2Collection col = st.Certificates;
  
              X509Certificate2 card = null;
              // X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, "Certificates", "Select one to sign", X509SelectionFlag.SingleSelection);
  
              if (col.Count &gt; 0)
              {
                  for (int i = 0; i &lt; col.Count; i++)
                  {
                      var cert = col[i];
  
                      // Log cert.FriendlyName
                      DecryptContent(data,cert);
                  }
              }
  
              st.Close();
          }
  
          public static void DecryptContent(byte[] data, X509Certificate2 certificate)
          {
              try
              {
                  RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)certificate.PrivateKey;
                  rsa.Decrypt(data, true);
              }
              catch (Exception e)
              {
                     // Log error info.
              }
          }
  </code></pre>