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! 🙂