Reputation: 13
I have created an RSA Key Container by using the following code.The keys are created in the container and I can encrypt/decrypt in the container successfully.
public static void CreateKeyContainer()
{
RSACryptoServiceProvider rsa = null;
try
{
var cryptoParameters = new CspParameters();
cryptoParameters.KeyContainerName = "MyContainer";
cryptoParameters.Flags = CspProviderFlags.UseMachineKeyStore;
rsa = new RSACryptoServiceProvider(2048, cryptoParameters);
}
finally
{
if (rsa != null)
{
rsa.Clear();
rsa.Dispose();
}
}
}
Before the call of the CreateKeyContainer method, I would like to ensure whether the keys already exist or not in the specified container. I have changed the flag to CpsProviderFlags.UseExistingKey.
public static bool CheckIfKeysExist()
{
RSACryptoServiceProvider rsa = null;
try
{
var cryptoParameters = new CspParameters();
cryptoParameters.KeyContainerName = "MyContainer";
cryptoParameters.Flags = CspProviderFlags.UseExistingKey;
rsa = new RSACryptoServiceProvider(2048, cryptoParameters);
}
catch (Exception ex)
{
return false;
}
finally
{
if (rsa != null)
{
rsa.Clear();
rsa.Dispose();
}
}
return true;
}
However, by executing this method, it always throws a Cryptographic Exception that "Keyset does not exist", regardless of the existence of the key container.
How can I check if the key container already exists?
Upvotes: 0
Views: 1639
Reputation: 870
Since you are creating the Key in Machine Key Store set the Flags property as shown below:
cryptoParameters.Flags = CspProviderFlags.UseExistingKey | | CspProviderFlags.UseMachineKeyStore;
Upvotes: 0