CryptographicException – “An internal error occurred”

I had some code that looked something like this…

byte[] certificate;
string certificatePassword;
var certificate = new X509Certificate2(certificate, certificatePassword);

…and it threw a CryptograhicException with the most unhelpful of error messages “An internal error occurred”.

I am running this code within a web-service and thus within IIS – As such the ‘user’ that this code is running under (the app pool user / IIS user) does not have the appropriate permissions to handle the above statement.  This is because the certificate will be temporarily stored in a certificate store, which by default is the user store, but the app pool / IIS user does not have rights to that certificate store.

To solve this issue we simply need to state that the certificate should be handled by the local computer store – by specifying an extra parameter of X509KeyStorageFlags.MachineKeySet.  This then solves the problem.  So, our code from earlier should simply look like below…

var certificate = new X509Certificate2(certificate, certificatePassword, X509KeyStorageFlags.MachineKeySet);

If you come across the same problem and this helps you then that’s great! 🙂

Advertisements

2 thoughts on “CryptographicException – “An internal error occurred”

  1. When running under a temporary or mandatory profile (typically on Citrix or appV) this problem crops up. We ended up writing our own .net wrapper for the crypto in order to avoid the issue.

    Source code: http://devnet.superoffice.com/Blog/My-Blog/?userId=4973&entryId=887

    Microsoft .net 4.0 updated the Cryptography wrappers so that they throw an exception when used on temporary profiles. The MachineKeySet flag avoids asking the user profile keystore, thus avoiding the exception. In .net 4 they added another flag to the enum for emphemeral keys (i.e. keys that come from memory buffers, not from a keystore) – but even that will sometimes trigger exceptions, due to the internal implementation of the .net wrapper.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s