Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use MachineKey.Protect Outside of ASP.NET

I need to encrypt a cookie outside of ASP.NET (Console App, Powershell etc.) but since this cookie will eventually be read by my MVC application it needs to be encrypted with the same key.

I can use the MachineKey class outside of ASP.NET however I can't specify the encryption type or key as these are outlined in the application's web.config which doesn't exists in this context. Since there is no config the key is randomly generated everytime.

How can I encrypt data using the same decryption key below so it is guaranteed to be decrypted successfully later by my MVC application?

<machineKey 
  validationKey="207FE3B8E01D0FF81871D7F3EFC082A14341A7820942D24D3BEF8954CAE53D860F46FBCDDA73F752CE1052D475D442CC8C14FC814739A757D52D152EF5EE179E"
  decryptionKey="326C47E59EB1B38AEA84DBC9633BB770C318A740E477C82F3A8D9506F030D953"
  validation="SHA1" decryption="AES"

/>
like image 736
heymega Avatar asked Jun 29 '15 15:06

heymega


1 Answers

Some possible ideas.

  1. Just use an App.config with your console app and mirror the machine key from the web.config of your main project.
  2. Grab the machine key programatically. To do this you would need the path of the machine key (perhaps you could store it in DB, windows registry, or somewhere?). MSDN has some great examples of this method.

Grabbing the key is basically:

Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);
MachineKeySection configSection = (MachineKeySection)config.GetSection("system.web/machineKey");

Then it is just a matter of using the right method to encrypt the cookie. Keep in mind that some ASP.NET membership providers serialize additional data into the cookie so depending on which one you are using, this may not be possible. Also, if your app uses the UserData section of a cookie then this could break it.

like image 132
Brad C Avatar answered Oct 04 '22 04:10

Brad C