MVC 5 encrypt parameters

 

This is an old idea that I was having. The problem was that , for many people, showing the parameters in MVC is not something that they want . For example. suppose that we have this action

 

public ActionResult TestEncrypt(int id, int a, string b)

 

The this action can be activated by putting in the Razor cshtml file this

 

<a href=’@Url.Action("TestEncrypt", new { id=7, a = 1, b = "asd" })’>Test</a>

 

that will generate this URL :

http://mvc5encrypt.apphb.com/Home/TestEncrypt/7?a=1&b=asd .

The parameters are passed in clear text ( a is 1 and b is asd). What if I want to encrypt those into the URL ,

http://mvc5encrypt.apphb.com/Home/TestEncrypt/7?a=EAAAAHT3XGpsOow%2f2Wto%2fho1C3Bmy1kTFnBosorsrt9X3Eqj&b=EAAAADbjm%2bS8NDAKqznGI%2bzF02oOAY9wf24SFyFxPxbCu0ea

 

but receive in the Action the default values ( 1 and asd)?

Enter MVC5Encrypt

What you have to do is modify slightly the code in the .cshtml and add an attribute to the Action

 

<a href=’@Url.ActionEnc("mySecret", "TestEncrypt", new { id=7, a = 1, b = "asd" })’>Test</a>

 

and the action will be

[MVCDecryptFilter(secret = &quot;mySecret&quot;)]   
public ActionResult TestEncrypt(int id, int a, string b)

 

You can see into action at

http://mvc5encrypt.apphb.com/Home/TestEncrypt/7?a=EAAAAHT3XGpsOow%2f2Wto%2fho1C3Bmy1kTFnBosorsrt9X3Eqj&b=EAAAADbjm%2bS8NDAKqznGI%2bzF02oOAY9wf24SFyFxPxbCu0ea

 

FAQ:

1.  What is “mysecret”?

See code on http://stackoverflow.com/questions/202011/encrypt-and-decrypt-a-string that I shameless copied.

 

2. What about backward compatibility ( i.e., old links will function ) ?

Yes if you do not already encode in base64 ( default class encrypter knows if the parameter value is in base64 ) . See

http://mvc5encrypt.apphb.com/Home/TestEncrypt/7?a=1&b=asd 

 

3. What about extending this with a custom encrypt class ?

You can – see this function

 

public static string ActionEnc(this UrlHelper helper, IEncryptDecrypt encDec, string actionName, object routeValues)

 

4. What about extending this to route parameters ( e.g. http://localhost/Person/Edit/5  – the 5 parameter is in the route and not encrypted ) ?

Glad you ask. Please fill an feature request on github

5. More details ? 

Sources on GitHub : https://github.com/ignatandrei/MVC5Encrypt

Demo at http://mvc5encrypt.apphb.com/ 

NuGet at https://www.nuget.org/packages/MVC5Encrypt/

( Other solution is to use http://madskristensen.net/post/httpmodule-for-query-string-encryption)