Search code examples
smartcardcng

Import key on a given token with CNG


I've recently started fiddling with CNG to manage smartcards in our applications, and something remains quite unclear: How do you import a key into a given smartcard ? It seems to me that the KSP just creates the key on the first card it sees.

Here's what I did:

  • 2 smartcards are connected to my machine, from the same vendor.
  • Said vendor implemented his own KSP, which appears when i list KSPs with NCryptEnumStorageProviders.
  • Listing the keys available through the provider produces the following output:

    Got key: p11#958fb9080419db6e //Belongs to 1st smartcard
    Got key: p11#9eaad58f1c3a73e5 //Belongs to 1st smartcard
    Got key: b6b99fb4-01c4-fa18-83db-0e2bb1c80476 //Belongs to 2nd smartcard

Now when i called NCryptCreatePersistedKey, the new key was generated on the 2nd card. No popup whatsoever asked me on which card i wanted to create this key.

What did i do wrong ?

Thanks a lot for your time.


Solution

  • Try to set smartcard reader explicitly in NCryptCreatePersistedKey:

    NCryptCreatePersistedKey(hProv, phKey, L"alg_id", L"\\\\.\\SmartCard Reader 0\\KeyName", 0, 0);