Certificates from SmartCard in C #

How can I provide access to certificates from my smart card and not create my own certificate store in C #? and how can I get my RSACryptoProvider to use the secret key of the smart card certificate?

thanks

Wally

+5
source share
2 answers

Sometimes, especially if you do not use the default container name on the smart card (Microsoft recommended), certificates are not copied to the local certificate store. The solution is to use crypto-api to access the key using KP_CERTIFICATE, create a certificate from the extracted data and assign it a new RSACryptoServiceProvider built using your own key container name.

Below is the C # pseudo code:

int reti = CryptoApi.CryptGetUserKey(_hprovider, keytype, ref userKey);

if (reti)
{
    reti =CryptoApi.CryptGetKeyParam(_userKey, KP_CERTIFICATE, ref  pbdata, ref pwddatalen, 0);
}

if (reti || pwddatalen>0)
{
    byte[] data = new byte[pwddatalen];
    ret  = CryptoApi.CryptGetKeyParam(_userKey, KP_CERTIFICATE, data, ref pwddatalen, 0);
    if (ret) 
    {
        X509Certificate2 c = new X509Certificate2(data);
        X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadOnly);
        X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint, c.Thumbprint, validonly);
        store.Close();

        if (col.Count != 1) 
        {
            //not found in store - CSP didn't copy it
            c.PrivateKey = PrivateKey(keytype);
            return c;
        }
        else
        {
            return col[0];
        }
    }
}


private RSACryptoServiceProvider PrivateKey (KeyType keytype)
{
    CspParameters csparms = new CspParameters();
    csparms.KeyContainerName = _containerName;
    csparms.ProviderName = _provider;
    csparms.ProviderType = 1;
    csparms.Flags = CspProviderFlags.UseMachineKeyStore | CspProviderFlags.UseExistingKey;
    csparms.KeyNumber = (int)keytype;

    return new RSACryptoServiceProvider(csparms);
}
+3
source

Cryptographic Service Provider (CSP) -. Windows (2000, XP Vista) , - -, . -. , (, ), -. - PIN-, . , , , -.

+2

All Articles