Sunday

Cryptography - Key set does not exist when trying to access private key through X509Certificate2

Simple Approach:

Run your worker process under "local system" account, "local system" account has full access to MachineKey store by default. Its not the most secure option, but if you are in rush and want to keep moving during your unit test, then this is the way to go.

Right Approach:

Provide appropriate permissions to your service account, which is running the worker process in IIS. If you are not the IT guy (who does everything) then, you probably want to follow the previous approach during your unit testing ONLY!.

Geek Approach:

Some time ago, I wrote a web app which was reading a .pfx file through X509Certificate2 class. It was working all fine until I started getting the error "Key set does not exist" at the line of code where I was trying to read the private key.

I was getting this error despite the fact that HasPrivateKey flag of X509Certificate2 object was returning true.

To fix this problem this is what I did:

1 - Write a custom impersonation class and impersonated the currently executed thread with a user who had "Read" access to MachineKey store.

2 - Initialized X509Certificate2 object as follows:

{
X509Certificate2 cert = new X509Certificate2(PFXfileName, password, X509KeyStorageFlags.PersistKeySet |  X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
}
3 - Executed the code and Voila!!!

4 - After the successful execution of the code I removed X509KeyStorageFlags.PersistKeySet and X509KeyStorageFlags.Exportable and code kept on working all fine.

No comments:

Post a Comment

Your comments are highly appreciated!