Tuesday 24 April 2018

How to Encrypt and Decrypt Query String in MVC 5.

Follow the below steps:
Step 1:
Create a new class file (somename.cs) in you project and just copy paste the below code.

Step 2:
Build your project once.
Step 3:
in the comments you have posted this piece of code
Hide   Copy Code
@Html.EncodedActionLink(item.StudentName, "Edit", "Employee", new { id = item.StudentID }, null)

So the Controller Name is "Employee" and the Action is "Edit"
Go to EmployeeController -> Edit Action and add the [EncryptedActionParameter] attribute to the action as below

Hide   Copy Code
 [EncryptedActionParameter]
 public ActionResult Edit(int? Id)
 {
// your code...
  }


Now it should work.
Note: In the article the author has used the below key for Encryption/Decryption, you can change it for your need.
Hide   Copy Code
string key = "jdsg432387#";


------------CREATE CLASS FILE -----------------------

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.Web.Routing;
using System.Security.Cryptography;
using System.IO;
using System;

public static class MyExtensions
{
    public static MvcHtmlString EncodedActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)
    {
        string queryString = string.Empty;
        string htmlAttributesString = string.Empty;
        if (routeValues != null)
        {
            RouteValueDictionary d = new RouteValueDictionary(routeValues);
            for (int i = 0; i < d.Keys.Count; i++)
            {
                if (i > 0)
                {
                    queryString += "?";
                }
                queryString += d.Keys.ElementAt(i) + "=" + d.Values.ElementAt(i);
            }
        }

        if (htmlAttributes != null)
        {
            RouteValueDictionary d = new RouteValueDictionary(htmlAttributes);
            for (int i = 0; i < d.Keys.Count; i++)
            {
                htmlAttributesString += " " + d.Keys.ElementAt(i) + "=" + d.Values.ElementAt(i);
            }
        }

        //What is Entity Framework??
        StringBuilder ancor = new StringBuilder();
        ancor.Append("<a ");
        if (htmlAttributesString != string.Empty)
        {
            ancor.Append(htmlAttributesString);
        }
        ancor.Append(" href='");
        if (controllerName != string.Empty)
        {
            ancor.Append("/" + controllerName);
        }

        if (actionName != "Index")
        {
            ancor.Append("/" + actionName);
        }
        if (queryString != string.Empty)
        {
            ancor.Append("?q=" + Encrypt(queryString));
        }
        ancor.Append("'");
        ancor.Append(">");
        ancor.Append(linkText);
        ancor.Append("");
        return new MvcHtmlString(ancor.ToString());
    }

    private static string Encrypt(string plainText)
    {
        string key = "jdsg432387#";
        byte[] EncryptKey = { };
        byte[] IV = { 55, 34, 87, 64, 87, 195, 54, 21 };
        EncryptKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        byte[] inputByte = Encoding.UTF8.GetBytes(plainText);
        MemoryStream mStream = new MemoryStream();
        CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(EncryptKey, IV), CryptoStreamMode.Write);
        cStream.Write(inputByte, 0, inputByte.Length);
        cStream.FlushFinalBlock();
        return Convert.ToBase64String(mStream.ToArray());
    }
}



[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class EncryptedActionParameterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {

        Dictionary<string, object> decryptedParameters = new Dictionary<string, object>();
        if (HttpContext.Current.Request.QueryString.Get("q") != null)
        {
            string encryptedQueryString = HttpContext.Current.Request.QueryString.Get("q");
            string decrptedString = Decrypt(encryptedQueryString.ToString());
            string[] paramsArrs = decrptedString.Split('?');

            for (int i = 0; i < paramsArrs.Length; i++)
            {
                string[] paramArr = paramsArrs[i].Split('=');
                decryptedParameters.Add(paramArr[0], Convert.ToInt32(paramArr[1]));
            }
        }
        for (int i = 0; i < decryptedParameters.Count; i++)
        {
            filterContext.ActionParameters[decryptedParameters.Keys.ElementAt(i)] = decryptedParameters.Values.ElementAt(i);
        }
        base.OnActionExecuting(filterContext);

    }

    private string Decrypt(string encryptedText)
    {
        string key = "jdsg432387#";
        byte[] DecryptKey = { };
        byte[] IV = { 55, 34, 87, 64, 87, 195, 54, 21 };
        byte[] inputByte = new byte[encryptedText.Length];

        DecryptKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        inputByte = Convert.FromBase64String(encryptedText);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(DecryptKey, IV), CryptoStreamMode.Write);
        cs.Write(inputByte, 0, inputByte.Length);
        cs.FlushFinalBlock();
        System.Text.Encoding encoding = System.Text.Encoding.UTF8;
        return encoding.GetString(ms.ToArray());
    }
}

No comments:

Post a Comment