Search code examples
c#rsa

CryptographicException: Key not valid for use in specified state


I am new to C#. I couldn't understand why it's creating issue.

            CspParameters cspParams = new CspParameters(24);
            cspParams.KeyContainerName = "XML_DISG_RSA_KEY";
            RSACryptoServiceProvider key = new RSACryptoServiceProvider(cspParams);

Below code is working fine in my local setup. But its not working in client.

They got below exception.

[CryptographicException: Key not valid for use in specified state. ]

   System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer) +4644432
   System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle) +69
   System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair() +92
   System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize) +173
   System.Security.Cryptography.RSACryptoServiceProvider..ctor(CspParameters parameters) +14

Could you please help me.


Solution

  • We ran into this same error message with similar code (with or without specifying the UseExistingKey flag) with one of our customers. They had gone through a move of all of their users from an old domain to a new one, and seemed to run into this error approximately after that. We weren't able to identify a specific cause, but we suspect that changing the ownership of the key container file (or it finding the matching key container file for the older user identity from the old domain still on the machine) might have violated security in the RSACryptoServiceProvider (or in the crypto API or underlying non-managed implementation).

    We ultimately solved it by manually identifying the key container file name (CspKeyContainerInfo.UniqueKeyContainerName) using test code on another computer, and then deleting the bad container file that was causing the error. The KeyContainerName you specify in the CspParameters maps to the same 32-hexadecimal-digit filename prefix each time, with the rest of the file name (apparently) being specific to the user who created it. The container files are stored in either the machine key store (if UseMachineKeyStore flag is specified) or in the user's key store in their roaming application data (typically %APPDATA%\Roaming\Microsoft\Crypto\ ...).

    Be careful not to break other key container files or you could break other apps or services on the machine.

    You might also see if specifying a key size in the constructor call helps when you're creating a new key. Try 1024, or these days maybe 2048.