Sunday, February 20, 2011

Unable to import a key into KeyNumber.Signature with RSACryptoServiceProvider

Hi all,

The other day a customer of mine was having an issue when importing key pairs with .NET's RSACryptoServiceProvider. When setting KeyNumber parameter to KeyNumber.Exchange everything seems to be fine. But when setting the KeyNumber parameter to KeyNumber.Signature the key pair is imported to the KeyNumber.Exchange slot just as if you haven’t set the KeyNumber parameter.
I could reproduce the issue with the following sample:

private void button1_Click(object sender, EventArgs e)
{
   // WORKS
   string keypair1 = GetKey(KeyNumber.Exchange);
   StoreKeyInContainer(KeyNumber.Exchange, keypair1);
   CheckKey(KeyNumber.Exchange, keypair1);
   // FAILS BUT IT SHOULD WORK
   string keypair2 = GetKey(KeyNumber.Signature);
   StoreKeyInContainer(KeyNumber.Signature, keypair2);
   CheckKey(KeyNumber.Signature, keypair2);
   // WORKS BUT IT SHOULD FAIL
   string keypair3 = GetKey(KeyNumber.Signature);
   StoreKeyInContainer(KeyNumber.Signature, keypair3);
   CheckKey(KeyNumber.Exchange, keypair3);
}
public static string GetKey(KeyNumber theKeyNumber)
{
   CspParameters parms;
   RSACryptoServiceProvider rsa;
   parms = new CspParameters(1);
   parms.Flags = CspProviderFlags.UseMachineKeyStore;
   parms.KeyNumber = (Int32)theKeyNumber;

Read more: Decrypt my World