locked
encrypt and decrypt query string RRS feed

  • Question

  • User-774158686 posted

    This code has been used to encrypt and decrypt query string .No matter what the lenght of the url is ,this code will encrypt the key and the value the query string into 25 digit

     

     


    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Collections.Specialized;
    using System.Collections;
    using System.Web;

     

    namespace BusinessLayer
    {
    public class QueryString : NameValueCollection
    {
    private string document;
    public string Document
    {
    get
    {
    return document;
    }
    }
    public QueryString()
    {
    }
    public QueryString(NameValueCollection clone): base(clone)
    {
    }
    //################################################## ###############################################
    //This Class Has been used to get the URl from the address browser of the page
    // http://www.hanusoftware.com
    //################################################## ###############################################
    //this method has been used to get the current URL of the page
    public static QueryString FromCurrent()
    {

    //returns the current url from the address bar
    return FromUrl(HttpContext.Current.Request.Url.AbsoluteUr i);

    }
    /// <summary>
    /// This method has been used to divide the Address URl into characters chunks
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public static QueryString FromUrl(string url)
    {
    //it breaks the address URL in array with separator of ? mark
    //this line breaks the Querystring and page
    string[] parts = url.Split("?".ToCharArray());
    //instantiate the class object
    QueryString qs = new QueryString();
    //assign the page address to the variable
    qs.document = parts[0];
    //if there is any data in array
    if (parts.Length == 1)
    return qs;
    //breaks the QueryString into characters chunks with separator mark &
    string[] keys = parts[1].Split("&".ToCharArray());
    foreach (string key in keys)
    {
    //again breaks into chunks by + mark
    string[] part = key.Split("=".ToCharArray());
    if (part.Length == 1)
    qs.Add(part[0], "");
    //adds the QueryString key and value pair to the assigned variable
    qs.Add(part[0], part[1]);
    }
    return qs;


    }
    /// <summary>
    /// This method clear all exceptions in the passed string
    /// </summary>
    /// <param name="except"></param>
    public void ClearAllExcept(string except)
    {
    //calls the method to clear except
    ClearAllExcept(new string[] { except });

    }
    /// <summary>
    /// this is the usual method which has to call clear all exceptions
    /// </summary>
    /// <param name="except"></param>
    public void ClearAllExcept(string[] except)
    {
    //take an arrayList
    ArrayList toRemove = new ArrayList();
    foreach (string s in this.AllKeys)
    {
    foreach (string e in except)
    {
    if (s.ToLower() == e.ToLower())
    if(!toRemove.Contains(s))
    toRemove.Add(s);

    }
    }
    foreach (string s in toRemove)
    this.Remove(s);
    }
    /// <summary>
    /// this method adds the key value pairs in QueryString of the URL
    /// </summary>
    /// <param name="name"></param>
    /// <param name="value"></param>
    public override void Add(string name, string value)
    {
    //checks nullability of the name
    if (this[name] != null)
    //if not null then assign value to it
    this[name] = value;

    else

    base.Add(name, value);

    }

     

    public override string ToString()
    {

    return ToString(false);

    }


    /// <summary>
    /// this ethod has been used to join all the characters array to the URL
    /// </summary>
    /// <param name="includeUrl"></param>
    /// <returns></returns>
    public string ToString(bool includeUrl)
    {

    string[] parts = new string[this.Count];

    string[] keys = this.AllKeys;
    //for each keys breaks the URL into chunks
    for (int i = 0; i < keys.Length; i++)

    parts[i] = keys[i] + "=" + HttpContext.Current.Server.UrlEncode(this[keys[i]]);

    string url = String.Join("&", parts);

    if ((url != null || url != String.Empty) && !url.StartsWith("?"))

    url = "?" + url;

    if (includeUrl)

    url = this.document + url;

    return url;

    }

    }

    }

     

    Software Development India

    Wednesday, June 6, 2007 4:05 AM

All replies

  • User472272724 posted

    This code is encrypt and decrypt whole website querystring without doing any coding in each page of website

    Create a new file in App_code folder with the name 
    QueryStringModule.cs

    ----
     
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;
    using System.Web;
    
    
    
        /// <summary>
        /// Summary description for QueryStringModule
        /// </summary>
        public class QueryStringModule : IHttpModule
        {
          //  private ILog m_Logger = LogManager.GetLogger(typeof(QueryStringModule));
            #region IHttpModule Members
    
            public void Dispose()
            {
                // Nothing to dispose
            }
    
            public void Init(HttpApplication context)
            {
                context.BeginRequest += new EventHandler(context_BeginRequest);
            }
    
            #endregion
    
            private const string PARAMETER_NAME = "enc=";
            private const string ENCRYPTION_KEY = "key";
    
            void context_BeginRequest(object sender, EventArgs e)
            {
                HttpContext context = HttpContext.Current;
                string query = string.Empty;
                string path = string.Empty;
    
                try
                {
                    if (context.Request.Url.OriginalString.Contains("aspx") && context.Request.RawUrl.Contains("?"))
                    {
                        query = ExtractQuery(context.Request.RawUrl);
                        path = GetVirtualPath();
    
                        if (query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase))
                        {
                            // Decrypts the query string and rewrites the path.
                            string rawQuery = query.Replace(PARAMETER_NAME, string.Empty);
                            string decryptedQuery = Decrypt(rawQuery);
                            context.RewritePath(path, string.Empty, decryptedQuery);
                        }
                        else if (context.Request.HttpMethod == "GET")
                        {
                            // Encrypt the query string and redirects to the encrypted URL.
                            // Remove if you don't want all query strings to be encrypted automatically.
                            string encryptedQuery = Encrypt(query);
                            context.Response.Redirect(path + encryptedQuery, false);
                        }
                    }
                }
                catch (Exception ex)
                {
                   // m_Logger.Error("An error occurred while parsing the query string in the URL: " + path, ex);
                    context.Response.Redirect("~/Home.aspx");
                }
    
            }
    
            /// <summary>
            /// Parses the current URL and extracts the virtual path without query string.
            /// </summary>
            /// <returns>The virtual path of the current URL.</returns>
            private static string GetVirtualPath()
            {
                string path = HttpContext.Current.Request.RawUrl;
                path = path.Substring(0, path.IndexOf("?"));
                path = path.Substring(path.LastIndexOf("/") + 1);
                return path;
            }
    
            /// <summary>
            /// Parses a URL and returns the query string.
            /// </summary>
            /// <param name="url">The URL to parse.</param>
            /// <returns>The query string without the question mark.</returns>
            private static string ExtractQuery(string url)
            {
                int index = url.IndexOf("?") + 1;
                return url.Substring(index);
            }
    
            #region Encryption/decryption
    
            /// <summary>
            /// The salt value used to strengthen the encryption.
            /// </summary>
            private readonly static byte[] SALT = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString());
    
            /// <summary>
            /// Encrypts any string using the Rijndael algorithm.
            /// </summary>
            /// <param name="inputText">The string to encrypt.</param>
            /// <returns>A Base64 encrypted string.</returns>
            private static string Encrypt(string inputText)
            {
                RijndaelManaged rijndaelCipher = new RijndaelManaged();
                byte[] plainText = Encoding.Unicode.GetBytes(inputText);
                PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);
    
                using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16)))
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(plainText, 0, plainText.Length);
                            cryptoStream.FlushFinalBlock();
                            return "?" + PARAMETER_NAME + Convert.ToBase64String(memoryStream.ToArray());
                        }
                    }
                }
            }
    
            /// <summary>
            /// Decrypts a previously encrypted string.
            /// </summary>
            /// <param name="inputText">The encrypted string to decrypt.</param>
            /// <returns>A decrypted string.</returns>
            private static string Decrypt(string inputText)
            {
                RijndaelManaged rijndaelCipher = new RijndaelManaged();
    
                byte[] encryptedData = Convert.FromBase64String(inputText);
                PasswordDeriveBytes secretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);
    
                using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
                {
                    using (MemoryStream memoryStream = new MemoryStream(encryptedData))
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                        {
                            byte[] plainText = new byte[encryptedData.Length];
                            int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
                            return Encoding.Unicode.GetString(plainText, 0, decryptedCount);
                        }
                    }
                }
            }
    
            #endregion
    
        }
    

    -------

    and insert a line in web.config

    <httpModules>

     <add type="QueryStringModule" name="QueryStringModule"/>

    </httpModules>


     <add type="QueryStringModule" name="QueryStringModule"/>
    </httpModules>





    Wednesday, January 6, 2010 4:29 AM
  • User151963429 posted

    Hi singal..This is very nice... Thank you..


    Thursday, March 18, 2010 1:27 AM
  • User-284153169 posted

    Gr8 example. keep coding..................................... 

    Friday, April 9, 2010 2:58 AM
  • User-1781874498 posted

    hey, gunjansinghal. this is very nice coding!!! thanks. And i have a question is about, how it apply in silverlight??

    mean is it possible in silverlight application able to decrypt the ciphertext??? coz i not able to get the query string in silverlight but aspx done it!!! thanks.

    Friday, April 16, 2010 4:15 AM
  • User1340475578 posted

    What a code sirji! Great! Extra ordinary... Excellant.

    Thank you very much.

    Saturday, May 8, 2010 6:02 AM
  • User488770411 posted

    Thanks alot  singhal , really it is great code.

     

    Tuesday, May 18, 2010 12:17 PM
  • User917890880 posted

    Thanks, its really a useful good code. 

    Wednesday, May 26, 2010 5:03 AM
  • User-466931016 posted

     hey thanks man...its a really good code....its working nice...thanks again....

    Thursday, May 27, 2010 8:21 AM
  • User-89633792 posted

    It is not working on IIS 7.0. Any idea about that.???

    Wednesday, June 9, 2010 11:09 PM
  • User151963429 posted

    Hi Deep,

                Could you please specify what is the error.

                And remember that IIS 7 Supports mainly two application pools.

               1) Classic .NET AppPool

               2)Default Pool (Integrated Mode).

    So if you are running under default pool all the hhtp handlers and modules should be registerd under

    <system.webServer>

    </system.webServer> tag in the web.config.

    So basically Yout httpmodule will be

    <system.webServer>

    <modules>
                <remove name="YourModuleName" />
                 <add type="YourModuleType" name="YourModuleName" />
    </modules>

    </system.webServer>


    Try this and let me know if there are any issues.



     

    Thursday, June 10, 2010 12:56 AM
  • User-1268895362 posted

    Hi gunjansinghal,

    a very nice and useful code...thanx for sharing with others.

    your code works fine on IIS 5 and 6 but for IIS 7 the web.config code should be like this

    <system.webServer>

    <modules>
                <add type="QueryStringModule" name="QueryStringModule"/>
    </modules>

    </system.webServer>


    instead of writing in <system.web> we have to write in <system.webserver>

    Thanx.

    Saturday, June 26, 2010 8:09 AM
  • User2024939479 posted

    Hi Singhal,

    This is a method is very nice & work fine .But the problem is, the postback event in the page ,cause the query string display  as plain text  .What is the solution for this ?

    Please reply..

    Friday, July 30, 2010 5:27 AM
  • User-924722106 posted

    As suggested i have modified web.config as

    <httpModules>     
          <add type="QueryStringModule" name="QueryStringModule" />
    </httpModules>

    While running the applicagtion i am getting error


    Could not load type 'QueryStringModule' ..  web.config line

    Any help?

    Wednesday, December 29, 2010 4:56 AM