How to check if a key already exists in container?
Asked Answered
S

1

8

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?

Screw answered 14/7, 2013 at 14:1 Comment(0)
K
9

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

Kepner answered 12/9, 2013 at 13:37 Comment(3)
Thanks for your answer, it works. But things have changed since July - I don't trust this mechanism any longer.Screw
don't forget to call provider.Dispose() after you instantiate it.Tagmemics
Woudn't it be called after leaving the scope?Kepner

© 2022 - 2024 — McMap. All rights reserved.