Friday, 4 October 2013

Read credentials from a smart card c# programming

If you are programming in windows, then once you insert the smart card into a reader, windows will fetch all the certificates to the certificate store. Then we can retrieve all the credentials in the certificate and thereby the smart card using the following code:

var smartCardCerts = new List<X509Certificate2>();
var myStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
foreach(X509Certificate2 cert in myStore)
{
  if( !cert.HasPrivateKey ) continue; // not smartcard for sure
  var rsa = cert.PrivateKey as RSACryptoServiceProvider;
  if( rsa==null ) continue; // not smart card cert again
  if( rsa.CspKeyContainerInfo.HardwareDevice ) // sure - smartcard
  {
     // inspect rsa.CspKeyContainerInfo.KeyContainerName Property
     // or rsa.CspKeyContainerInfo.ProviderName (your smartcard provider, such as 
     // "Schlumberger Cryptographic Service Provider" for Schlumberger Cryptoflex 4K
     // card, etc
     var name = cert.Name;
     rsa.SignData(); // to confirm presence of private key - to finally authenticate
  }
}

1 comment:

  1. We were using this method in Windows 7 just fine, but in Windows 10, it pops up with a Windows Security message box saying that the smart card cannot perform the requested operation or hte operation requires a different smart card when it's trying to read the privatekey.

    ReplyDelete