Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a key already exists in container?

I'm building an application for secure messaging between multiple clients. In order to achieve that, I encrypt the message with AES, then I encrypt the AES key with the recipients public RSA key, then I send these two components (RSA-encrypted AES key and AES-encrypted message) to the recipient. The whole process works well and without any errors.

Now I ran into a problem and I'm wondering what would be the best practice: In order to persist the private and public key of one participent, I need to store the key pair. Saving it somewhere as an XML file is possible, but obviously not an option. So decided to use a key container as described here. Implementing the use of the container is quite easy, but how can I

  1. Check if a specified container already exists?
  2. Check if the key size matches a given value?

As far as I can see this is not possible, because the RSACryptoServiceProvider generates a new key if the container does not exist - without telling so. But I need to know if there is a previously stored key pair available or if a new one is created.

How can I fix that? Or is this a completely wrong approach?

like image 680
Rob Avatar asked Jul 14 '13 14:07

Rob


1 Answers

Try this:

    public static bool DoesKeyExists(string containerName)
    {
        var cspParams = new CspParameters
        {
            Flags = CspProviderFlags.UseExistingKey,
            KeyContainerName = containerName
        };

        try
        {
            var provider = new RSACryptoServiceProvider(cspParams);
        }
        catch (Exception e)
        {
            return false;
        }
        return true;
    }

similiar question: How to check if RSA key container exists in .NET

like image 73
hdev Avatar answered Nov 16 '22 09:11

hdev