"Error occurred during a cryptographic operation" when decrypting Forms cookie
Asked Answered
I

15

55

I've uploaded my website to a webhosting and this error came up;
'Error occurred during a cryptographic operation.'.

I've done some research and it seems that the formauthenticated cookie is bound to the MachineKey (which differs when using webhost).


I've found a method that should fix this problem but the error remains.

CODE:

/// <summary>
    /// This method removes a cookie if the machine key is different than the one that saved the cookie;
    /// </summary>
    protected void Application_Error(object sender, EventArgs e)
    {
        var error = Server.GetLastError();
        var cryptoEx = error as CryptographicException;
        if (cryptoEx != null)
        {
            FederatedAuthentication.WSFederationAuthenticationModule.SignOut();
            Global.Cookies.FormAuthenticated Cookie = new Global.Cookies.FormAuthenticated();
            Cookie.Delete();
            Server.ClearError();
        }
    }


STACKTRACE:

[CryptographicException: Error occurred during a cryptographic operation.]
   System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.HomogenizeErrors(Func`2 func, Byte[] input) +115
   System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.Unprotect(Byte[] protectedData) +59
   System.Web.Security.FormsAuthentication.Decrypt(String encryptedTicket) +9824926
   Archive_Template.Main.resolveLoginUser(String sessionKey) in f:\Archive_Template\Archive_Template\Main.aspx.cs:481
   Archive_Template.Main.OnPreInit(EventArgs e) in f:\Archive_Template\Archive_Template\Main.aspx.cs:52
   System.Web.UI.Page.PerformPreInit() +31
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +335
Ironmonger answered 15/9, 2014 at 21:58 Comment(2)
If you're using server-side ADAL libraries from Microsoft, see @FRoZeN's answer (delete the cached tokens from you SQL 'UserTokenCaches' table)Comber
If you're doing client side scripting / SPA development, see @BaqerNaqvi's answer - clearing your browser's localStorage where ADAL.js is storing and caching it's API access tokens should help resolve thingsComber
A
36

For anyone who hasn't solved their problem, I was missing the "machineKey" entry for encrypt/decrypt in my web.config

Austronesia answered 15/9, 2015 at 14:33 Comment(3)
Can you expand on this answer? What particular config did you use? Can this be configured with iis?Curet
You can add something like this inside the system.web section in the WebConfig. <machineKey validationKey="AutoGenerate,IsolateApps" decryptionKey="AutoGenerate,IsolateApps" validation="HMACSHA256" decryption="Auto" /> However, that does not fix the issue permanently. check the comments in #14120465 and for the IIS blogs.msdn.microsoft.com/amb/2012/07/31/…Deuce
I had this issue moving a site into a web farm with two web servers. This answer, using Juan Acosta's link, plus clearing the cached data and cookies for this site only (I did this using the browser developer tools), as suggested by andreasnico's answer, solved the problem. Thank you.Insufferable
P
37

I faced the same problem. I just cleared all of browser's cookies and cache data and it got fixed.I hope it will work for you too.

Pericarp answered 19/7, 2016 at 14:40 Comment(3)
Thanks! Fixed my issueCrine
I also ran into this issue and clearing cookies worked. The Stack Trace message had a lot of calls regarding session security and session authentication. Cookies was definitely the issue!Peruzzi
Many thanks, it worked like a magic. I was stuck since two days due to this. I should've checked it on stackoverflow first :DGeophyte
A
36

For anyone who hasn't solved their problem, I was missing the "machineKey" entry for encrypt/decrypt in my web.config

Austronesia answered 15/9, 2015 at 14:33 Comment(3)
Can you expand on this answer? What particular config did you use? Can this be configured with iis?Curet
You can add something like this inside the system.web section in the WebConfig. <machineKey validationKey="AutoGenerate,IsolateApps" decryptionKey="AutoGenerate,IsolateApps" validation="HMACSHA256" decryption="Auto" /> However, that does not fix the issue permanently. check the comments in #14120465 and for the IIS blogs.msdn.microsoft.com/amb/2012/07/31/…Deuce
I had this issue moving a site into a web farm with two web servers. This answer, using Juan Acosta's link, plus clearing the cached data and cookies for this site only (I did this using the browser developer tools), as suggested by andreasnico's answer, solved the problem. Thank you.Insufferable
G
20

If you are using forms auth. you can signout when you catch the exception and allow your users to login and create a valid cookie

catch (CryptographicException cex)
{
    FormsAuthentication.SignOut();
}
Grodno answered 5/10, 2014 at 17:2 Comment(4)
Hello, I have the same problem, can you tell me where should I put this code in my controllers to catch this error?Side
On your Global.asax fileVladi
We are facing this issue at login for some users onlyMccurry
Place this code where you create your authentication cookie(s).Grodno
I
9

This is due to the machine key is missing, which is used as a symmetric key to do the encryption and decryption.

To set the machine in the IIS;

Go to your application -> Machine Keys -> Generate Keys

Incompetent answered 12/3, 2015 at 10:32 Comment(0)
G
9

I ran into this problem when I tried to take a forms authentication cookie created by an ASP.NET 2.0 app and decrypt it inside an .NET4.5 Web API project. The solution was to add an attribute called "compatibilityMode" to the "machineKey" node inside my web api's web.config file:

<machineKey 
...
compatibilityMode="Framework20SP2"/>

Documentation: https://msdn.microsoft.com/en-us/library/system.web.configuration.machinekeysection.compatibilitymode.aspx

And from the doc, here are the allowed values for that attribute:

  • Framework20SP1. This value specifies that ASP.NET uses encryption methods that were available in versions of ASP.NET earlier than 2.0 SP2. Use this value for all servers in a web farm if any server has a version of the .NET Framework earlier than 2.0 SP2. This is the default value unless the application Web.config file has the targetFramework attribute of the httpRuntime element set to "4.5".
  • Framework20SP2. This value specifies that ASP.NET uses upgraded encryption methods that were introduced in the .NET Framework 2.0 SP2. Use this value for all servers in a web farm if all servers have the .NET Framework 2.0 SP2 or later but at least one does not have the .NET Framework 4.5.
  • Framework45. Cryptographic enhancements for ASP.NET 4.5 are in effect. This is the default value if the application Web.config file has the targetFramework attribute of the httpRuntime element set to "4.5".
Gleeful answered 23/11, 2016 at 18:46 Comment(1)
This, coupled with the solution to this: #16661400, solved my problem. Thanks!Cerecloth
V
9

I just had this aswell, i deleted the UserTokenCaches table entries from the database.

Vogt answered 23/1, 2017 at 7:29 Comment(1)
Yes, for users of the ADAL libraries from Microsoft.. delete your tokens cached in the database.. just like @FRoZeN says hereComber
D
7

Another option is to clear the cookies from browser setting and this allows new cookies to get stored.

Debunk answered 23/2, 2018 at 8:59 Comment(1)
Closed all my browser, open a new one and this issue is goneOdalisque
D
6

I have also experienced this when developing a new solution and running the website on localhost. Setting the machinekey made no difference, but simply deleting all the cookies for localhost solved the problem.

Dolce answered 4/12, 2015 at 7:22 Comment(0)
T
5
       protected void Application_Error(object sender_, CommandEventArgs e_)
    {
        Exception exception = Server.GetLastError();
        if(exception is CryptographicException)
        {
            FormsAuthentication.SignOut();
        }
    }

in your Global.asax.cs, from Catching errors in Global.asax, as long as you use Forms authentication (login/password). Worked for me.

Trustless answered 31/8, 2017 at 13:12 Comment(0)
C
2

If you receive this error when implementing single sign on (as described here http://www.alexboyang.com/2014/05/28/sso-for-asp-net-mvc4-and-mvc5-web-apps-shared-the-same-domain/), make sure to have the same target framework across all projects. I had one project with .NET 4.0 and the other on .NET 4.5.2.

Changing the first one to 4.5.2 fixed the issue for me.

Cratch answered 29/6, 2016 at 5:48 Comment(1)
Going to the Project and specifying .Net 4.5.2 again seemed to fix the issue for me, as well.Dancette
D
2

I was getting crypto errors when validating the AntiForgery token.

I believe it was because I had just made some security control configuration changes to my server to configure application recycling to recycle when Virtual Memory limits hit 1,000,000 Kilobytes.

This was definitely way too little for virtual memory recycling. Private memory usage can be set to 1,000,000 KB, but virtual memory should be given a lot more space.

I noticed my application was recycling much too often.

I increased the Virtual Memory limit to 10,000,000 KB and those errors went away. I believe the application pool may have been recycling as I was filling out the form.

Dancette answered 3/4, 2018 at 11:31 Comment(0)
D
1

For me, It was the <httpRuntime targetFramework="4.7.2"/> causing the compatibilty issues.My application was not using targetFramework="4.7.2" parameter in <httpRuntime targetFramework="4.7.2"/> in the web.config while the webApi was using <httpRuntime targetFramework="4.7.2"/> .Removing the paramater from the WebApi or adding the paramater in the Application did the trick.

Dirge answered 18/5, 2020 at 11:43 Comment(0)
I
1

I had this problem when somebody decided to change the encryption algorithm to DES (a very old standard of encryption). Moving it back to AES (a more modern encryption standard) cleared the error.

Might have been something to do with Group Policy disabling DES...

The encryption algorithm is hidden in the Machine Key section (with IIS). There's probably a way of setting it in the web.config also.

Intercut answered 1/12, 2020 at 14:41 Comment(1)
In my case problem occurred when target framework was raised from 4.0 to 4.8. Existing machine key was generated using DES algorithm but DES is deprecated for .NET Framework 4.8. Generating new machine key using AES solved the problem.Skricki
E
0

I had the same issue: MVC 5 ASP.Net Web Application .net Framework 4.6.1

Solution:

  1. Go to App_Data folder (Solution explorer)
  2. Double click in your NAME.mdf (this action open Server Explorer Tab)
  3. Right click on UserTokenCaches table and view Show Table Data
  4. Delete the row
  5. Run app again and everything will be ok
Emaemaciate answered 10/6, 2017 at 18:13 Comment(0)
F
0

In my case the problem was an error in the configuration of the application pool in IIS.

In the the "Advanced settings" of the application pool the setting "Load User Profile" needs to be set to "true".

Floyfloyd answered 31/1 at 7:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.