Search code examples
c#asp.netsecurityencryption-asymmetric

system cannot find the file specified exception, when i want to save RSA Key in Key Container


I want to upload a text file that contains my private key to save in Key Container on web host.

I use below to save the keys:

var pk = Encoding.UTF8.GetString(fuPrivateKey.FileBytes);
CspParameters csp = new CspParameters();
csp.KeyContainerName = "Name";
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, csp);
rsa.FromXmlString(pk);
Message = "Key Saved";

and this for encryption and decryption:

CspParameters csp = new CspParameters()
{
       KeyContainerName = "Name",
       Flags = CspProviderFlags.UseExistingKey
};
      RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, csp);

I don't have in localhost but I got below error in web host when i want to save keys:

Exception Details: System.Security.Cryptography.CryptographicException: The system cannot find the file specified.

Then I used csp.Flags = CspProviderFlags.UseMachineKeyStore; while storing keys and my problem is solved but when i want to see if the key is exists like below it seems that doesnt exsit.(and problem in encrypting and decrypting)

How should I use flag some way that my problem will be solved?


Solution

  • I used CspParameters with the below flag when i want to store the keys:

    Flags = CspProviderFlags.UseMachineKeyStore;
    

    and the below flag when i want to encrypt ,decrypt and check existing of keys:

    Flags = CspProviderFlags.UseExistingKey|CspProviderFlags.UseMachineKeyStore;