CryptographicException: The handle is invalid
October 31, 2008 8 Comments
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:
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 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:
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.