Tuesday 12 April 2016

encode and decode query string asp.net

Use below code to encode the query string using AntiXSS library for it you need to refer the antixss library in your code.

What is Antixsslibrary ?
It helps you to protect your code from cross site scripting. It helps to encode the text.
Cross site scripting (XSS) occurs  mostly on  due following .
1. When Dynamically data changing.
2. Passing the data through query string.
3. Displaying data to UI which is allowing to insert from user (they can insert the script aswell)
4. Showing any messages to UI.



Classic XSS vulnerability.

1. Showing records Inserting from input control. Use AntiXssLibrary to encode the text.
Label1.Text = inp.value

To avoid it need to use like,
Label1.Text =  AntiXSSLibrary.HtmlEncode(inp.value)

2. Showing records got from Query control. Use AntiXssLibrary to encode the text.
Label1.Text = Request.QueryString["Value"];

To Avoid it need to use like
Label1.Text = AntiXssLibrary.HtmlEncode(Request.QueryString["Value"]);


Code Snippet

/// <summary>
        /// HtmlEncode the QString
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private static string EncodeQString(string value)
        {
            //                    value = HttpContext.Current.Server.HtmlEncode(value);
            value = Microsoft.Security.Application.AntiXSSLibrary.HtmlEncode(value);
            return value.Replace("'", SingleQuoteEncoding);
        }

Decode query string.

 /// <summary>
        /// HtmlDeCode the QString
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private static string DeCodeQString(string value)
        {
            value = value.ToString().Replace(SingleQuoteEncoding, "'");
            return HttpContext.Current.Server.HtmlDecode(value);
        }


No comments:

Post a Comment