CryptographicException: The handle is invalid


The Problem

I was recently working on a method to load a X509 certificate from the server’s certificates store. While my code worked fine on my local machine, I kept getting a System.Security.Cryptography.CryptographicException saying that the handle was not valid after deploying to our test server. I made sure that the certificate was present in the store.

The code I was using to read the certificate looked something like this:

   1: using System.Security.Cryptography.X509Certificates;
   2: ...
   3:     private X509Certificate2 GetCertFromStore(StoreName name, StoreLocation location, X509FindType findType, Object value)
   4:     {
   5:         X509Store store = new X509Store(name, location);
   6:         X509Certificate2 cert = null;
   7:         try
   8:         {
   9:             store.Open(OpenFlags.ReadOnly);
  10:             cert = store.Certificates.Find(findType, value, False)[0];
  11:         }
  12:         finally
  13:         {
  14:             if (store != null)
  15:                 store.Close();
  16:         }
  17:         return cert;
  18:     }
  19: }

Why is it happening?

It came down to a permissions issue. On my local machine, I am an administrator and I had the rights to read the certificate. However, the account my application was running under on the test server did not have the necessary permissions to read the certificate or the Private Key File to be exact.

The Solution

The solution is to give the account read rights to the certificate and this can be achieved using the Certificates Tool from WSE 3.0. WSE 3.0 is the latest version of Web Service Enhancements for .NET and can be downloaded here.

After you open the tool, you will be presented with a window like this one:

image

Choose the location of the certificate for which you want to alter permissions (in my case it is on the Local Computer in the Personal store) and click on Open Certificate. This will open another dialog allowing you to pick which certificate you want to work with in case you have more than one in the store.

To update the permissions, you need to click on the View Private Key File Properties… button. The dialog that opens is the usual file properties dialog so it should look familiar and updating the security settings should be straight forward. You only need to allow Read & Execute and Read permissions for the account running your app.

cert_permisssions

Advertisements