1

I found this article in Rahul's Blog about getting the certificate associated with the inserted smart card. Rahul suggests this approach:

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
  }
}

However, if the smart card is not inserted, a Windows Security dialog pops up asking the user to select a smart card device.

Is there a way to prevent this popup and instead throw an exception immediately?

Most important to me is this piece of information:

rsa.CspKeyContainerInfo.HardwareDevice 

Does somebody know any other way to access this info without popup dialogs if smart card is missing?

Edit:

The Windows Security dialog pops up at this line of code:

var rsa = cert.PrivateKey as RSACryptoServiceProvider;
Pete
  • 265
  • 6
  • 24
  • thanks for your help. unfortunately, it does not get me any further. the Windows Security dialog pops up even before the container is accessible. It happens at this line: `var rsa = cert.PrivateKey as RSACryptoServiceProvider;` – Pete Oct 02 '18 at 13:17
  • You could possibly use the PCSC API - there is one for C# it seems - and check if there is a smart card inside. It may be trickier to detect if it is the correct smart card though. – Maarten Bodewes Oct 03 '18 at 05:10

1 Answers1

0

There is no way to prevent the popup using this code. There are other approaches, for example using PCSC or Setting the PIN of a smartcard programmatically

Pete
  • 265
  • 6
  • 24