I have an application running on windows where I want to sign data with any smart card certificate.
Sory for my english, its not my native language. Here is code what I use:
string heslo = "289-Black Joe";
var myStore = new X509Store();
myStore.Open(OpenFlags.ReadOnly);
foreach(X509Certificate2 cert in myStore.Certificates)
{
if(!cert.HasPrivateKey) continue; // not smartcard for sure
try
{
var rsa = cert.PrivateKey as RSACryptoServiceProvider; // exception here
if(rsa == null) continue; // not smart card cert again
if(rsa.CspKeyContainerInfo.HardwareDevice) // sure - smartcard
{
signedHash = rsa.SignHash(HashData(heslo), CryptoConfig.MapNameToOID("SHA1"));
var pom = Encoding.Default.GetString(signedHash);
myStore.Close();
return;
}
} catch(Exception ex)
{
Console.WriteLine(ex);
}
}
myStore.Close();
The code work when in the project setting in Build->Platform target->Prefer 32-bit is checked. When iterating certificates get to the card certificate it request PIN code to card and then my data are signed. But when the "Prefer 32-bit" is unchecked (thats what I need) the window for request PIN code is skiped becouse cannot get private key of certificate.
I am not really sure why this is happening and I am also not really familiar working with certificates.