HI WELCOME TO KANSIRIS

Encrypt and Decrypt URL in MVC 4

Leave a Comment
In the below post we are going to learn about how we can implement a custom URL encryption and decryption logic in MVC 4 .
For encrypt and Decrypt URL in MVC with Area Name click here.
This post will teach you below
  1. How to create custom helper
  2. How to create custom Attribute and apply them to MVC
So, Lets start from creating custom ActionLinkHelper 
Create a static class “MyExtensions” and  update the code as below.In the below code I have created a custom helper “EncodedActionLink” which will generate the encoded URL

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

namespace kansiris.Web.Helper{  
  public static class anchorencript    {    
    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));    
            string stringToEncrypt = queryString;                encptdecpt encript = new encptdecpt();     
           string encripted = encript.Encrypt(stringToEncrypt);
                ancor.Append("?ks=" + encripted);  
          }            ancor.Append("'");            ancor.Append(">");          
  ancor.Append(linkText);        
    ancor.Append("");         
   return new MvcHtmlString(ancor.ToString());        }


        public static MvcHtmlString EncodedActionLink1(this HtmlHelper htmlHelper,  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(" href='");      
      if (controllerName != string.Empty)            {                ancor.Append("/" + controllerName);            }
            if (actionName != "Index")            {                ancor.Append("/" + actionName);            }  
          if (queryString != string.Empty)            {                // ancor.Append("?q=" + Encrypt(queryString));                string stringToEncrypt = queryString;                encptdecpt encript = new encptdecpt();        
        string encripted = encript.Encrypt(stringToEncrypt);
                ancor.Append("?ks=" + encripted);            }            ancor.Append("'");                       ancor.Append("");        
    return new MvcHtmlString(ancor.ToString());        }    }
}
After updating the code rebuild the project you are ready to render encrypted URL , just you need to call it as regular helper in the views also please add the using directive for your helper in the view page as below

@using kansiris.Web.Helper
now you can use your helper as below.(using @Html and pressing “.” should show you your custom helper)

                                    @Html.EncodedActionLink("Engagement", "Index", "NLiveDeals", new { eve = "Engagement" }, null)



create class in application

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

namespace MaaAahwanam.Utility{   
 public class encptdecpt    {        private byte[] key = { };        private byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };       
 string sEncryptionKey = "r0b1nr0y";
        public string Decrypt(string stringToDecrypt)        {            byte[] inputByteArray = new byte[stringToDecrypt.Length + 1];        
    try            {                key = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey);                DESCryptoServiceProvider des = new DESCryptoServiceProvider();       
         inputByteArray = Convert.FromBase64String(stringToDecrypt);           
     MemoryStream ms = new MemoryStream();                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);  
              cs.Write(inputByteArray, 0, inputByteArray.Length);         
       cs.FlushFinalBlock();                System.Text.Encoding encoding = System.Text.Encoding.UTF8;                return encoding.GetString(ms.ToArray());            }            catch (Exception e)            {                return e.Message;            }        }
        public string Encrypt(string stringToEncrypt)        {            try            {
                key = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey);  
              DESCryptoServiceProvider des = new DESCryptoServiceProvider();             
   byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);             
   MemoryStream ms = new MemoryStream();                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);  
              cs.Write(inputByteArray, 0, inputByteArray.Length);             
   cs.FlushFinalBlock();         
       return Convert.ToBase64String(ms.ToArray());            }            catch (Exception e)            {                return e.Message;            }        }    
    }}


user the following code to decrypt where ever you want in application in controller 


 if (ks != null)                {                    encptdecpt encript = new encptdecpt();                    string decripted = encript.Decrypt(ks);
                    string[] arrMsgs = decripted.Split('&');

                    string[] arrIndMsg;                    string strName = "";//, strAge = "", strPhone = "";                    arrIndMsg = arrMsgs[0].Split('='); //Get the Name                    strName = arrIndMsg[1].ToString().Trim();                    arrIndMsg = arrMsgs[1].Split('='); //Get the Age                    strAge = arrIndMsg[1].ToString().Trim();                    arrIndMsg = arrMsgs[2].Split('='); //Get the Phone                    strPhone = arrIndMsg[1].ToString().Trim();
                }

for encryption

  string stringToEncrypt = queryString;
                encptdecpt encript = new encptdecpt();
                string encripted = encript.Encrypt(stringToEncrypt); 

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.