Why do I get an Access Denied error when creating an X509Certificate2 object?

Using the "X509KeyStorageFlags.UserKeySet" flag in the X509Certificate2 constructor helped me.


This is my best guess about what's going on.

The X509Certificate2 constructor creates temporary public/private key objects in the Machine Keys directory (I believe via the Windows local security authority). Because the our unprivileged user doesn’t have access to these keys or the Machine Keys directory, the tests fail.

Our solution was to update our environment setup scripts to install these test certificates ahead of time, grant the unprivileged user permissions to them, and re-write the tests to load the certificates from the appropriate certificate store.