4

I am generating key pair and store them in xml file using

ToXmlString(true);

I need to set the key size to 2048 according to the MSDN the only place to do this is from the constructor of the RSACryptoServiceProvider

    private void AssignParameter(ProviderType providerType)
    {
        CspParameters cspParams;

        cspParams = new CspParameters((int)providerType);
        cspParams.KeyContainerName = RSAEncryption.containerName;
        cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
        cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";
        cspParams.KeyNumber = (int)KeyNumber.Exchange;

        this.rsa = new RSACryptoServiceProvider(2048, cspParams);
    }

when I check the key size using

int x = this.rsa.KeySize;

I always get 1024 so whats the wrong here??

muhammadelmogy
  • 153
  • 2
  • 9
  • 2
    Your code worked for me and I got 2048 back. What are you passing for providerType? I used a value of 1 (PROV_RSA_FULL) when creating cspParams. I also passed my own string into cspParams.KeyContainerName. – irritate Feb 19 '11 at 07:14
  • I am using the PROV_RSA_FULL also with the value of 1 and also my one string to the KeyContainerName property ! – muhammadelmogy Feb 19 '11 at 07:23
  • I am getting " Message Object already exists." – Rahul May 25 '17 at 10:57

2 Answers2

3

I've seen this before, try changing the container name or try

using (this.rsa = new RSACryptoServiceProvider(2048, cspParams)) 
{

}

or this.rsa.Clear(); after you are done with it.

If you already have a container with the same name it will re-use the container I believe.

lee-m
  • 2,269
  • 17
  • 29
Bill C
  • 31
  • 2
  • yes noticed same problem, deleted the container and imported a larger key, still fails. Created a new container with different name and it worked fine ! – xrcsblue Mar 24 '13 at 14:22
1

You need first to clear the existing container like this:

rsa.PersistKeyInCsp = false;
rsa.Clear();

Then it should work with you. Don't forget to set:

rsa.PersistKeyInCsp = true;
Tunaki
  • 132,869
  • 46
  • 340
  • 423