Wednesday, September 2, 2015

Error occurred during a cryptographic operation. System.Security.Cryptography.CryptographicException: Error occurred during a cryptographic operation.

I build a web application that worked in Dev and QA, but then demonstrated some unpredictable behavior in production, where it was load balanced between 2 servers.  The error log reported the following error:

Error occurred during a cryptographic operation.
System.Security.Cryptography.CryptographicException: Error occurred during a cryptographic operation.
   at System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.HomogenizeErrors(Func`2 func, Byte[] input)

This has to do with the Machine Key, which is used for decrypting and encrypting resources.  By default, the machine key is auto-generated by IIS.  The default works fine if your application is only running on one server.  But if the application is hosted across multiple servers, the application needs to be configured to use the same Machine Key across all servers.

I found a bunch of posts about this error.  I then populated a web.config section for my application that looked like this:

    <machineKey 
        decryptionKey="ABCDEFGH....." 
        validationKey="ABCDEFGHIJKLMNOPQRSTUVWXY....." 
        validation="SHA1"
        decryption="Auto"
    />

This key belongs in the <system.web> section.

I generated the keys using IIS:
http://docs.orchardproject.net/Documentation/Setting-up-a-machine-key

Here is the post related to this issue:
http://stackoverflow.com/questions/3855666/adding-machinekey-to-web-config-on-web-farm-sites