I want to encrypt query string values passing from grid view row hyperlink selection in asp.net because to prevent SQL injection attack. I am interested to do that work in UrlRewriting method or Encryption method. Which one method is good to use? How to do that?
-
1Why do you want to encrypt those parameters? – Darin Dimitrov Dec 23 '12 at 18:08
-
@DarinDimitrov To make sure nobody fiddles with the querystring? – Pleun Dec 23 '12 at 19:20
-
possible duplicate of [Encrypt Query String including keys](http://stackoverflow.com/questions/9110561/encrypt-query-string-including-keys) – Aristos Dec 23 '12 at 20:21
-
@Senthil Nathan: Please vote up any answers which you find valuable with up arrows and accept the best answer by clicking the tick. – Stephen Oberauer Dec 24 '12 at 12:19
3 Answers
The following code converts "firstName=stephen&surname=oberauer" to "arg=x2lk1rkBmXvilYTzLpfm5E9tkYSzEZnSkl7se0hNP0HsXbD82OYfiA==" and back.
Here's a simple encryption / decryption class (make sure to use your own key)
public static class Crypt
{
// Must be random
private static readonly byte[] key = new byte[24] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4 };
public static string Encrypt(string input)
{
byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);
TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
tripleDES.GenerateKey();
tripleDES.Key = key;
tripleDES.Mode = CipherMode.ECB;
tripleDES.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tripleDES.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
tripleDES.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public static string Decrypt(string input)
{
byte[] inputArray = Convert.FromBase64String(input);
TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
tripleDES.Key = key;
tripleDES.Mode = CipherMode.ECB;
tripleDES.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tripleDES.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
tripleDES.Clear();
return UTF8Encoding.UTF8.GetString(resultArray);
}
}
Assuming you had a grid view which looked like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="Url" DataTextField="Name" />
</Columns>
</asp:GridView>
You could set your grid data like this:
var gridData = new[]
{
new { Name = "Link 1", Url = "TargetPage.aspx?arg=" + Crypt.Encrypt("firstName=stephen&surname=oberauer") },
new { Name = "Link 2", Url = "TargetPage.aspx?arg=" + Crypt.Encrypt("firstName=joe&surname=smith") }
};
GridView1.DataSource = gridData;
GridView1.DataBind();
In your target page you could decode the encrypted query string like this:
var encryptedArgs = Request.QueryString["arg"];
var decryptedArgs = HttpUtility.ParseQueryString(Crypt.Decrypt(encryptedArgs));
FirstName.Text = decryptedArgs["firstName"];
Surname.Text = decryptedArgs["surname"];
In order to make sure that your query string was not tampered with you can handle the FormatException raised by the Decrypt method and test to make sure that the arguments exist, in this case "firstName" and "surname".
URL rewriting is a separate issue, which you can use if you want to make your URL prettier. It doesn't really have much to do with making sure that nobody fiddles with the query string.

- 5,237
- 6
- 53
- 75
why to complicate , you can use row databound event for set the Uri , convert you querystring parameter and use Server.UrlEncode, and you are good to go
RowDataBoundEvent
protected void YourGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType != DataControlRowType.DataRow) return;
if (e.Row.DataItem == null) return;
var hlobj= e.Row.FindControl("HYPERLINKID") as HyperLink;
if ( null == hlViewTest) return;
hlobj.NavigateUrl = String.Format("--------.aspx?whatever={0}",
Server.UrlEncode(Encrypt(whatever)));
}
catch (Exception ex)
{
//
}
}
Encryption Method :..........
private static string Encrypt(String val)
{
try
{
var bytes = Encoding.UTF8.GetBytes(val.ToString(CultureInfo.InvariantCulture));
var encBytes = ProtectedData.Protect(bytes, new byte[0], DataProtectionScope.LocalMachine);
return Convert.ToBase64String(encBytes);
}
catch (Exception ex)
{
return String.Empty;
}
}
Decryption Method :------------
private static string Decrypt(string val)
{
try
{
var bytes = Convert.FromBase64String(val);
var encBytes = ProtectedData.Unprotect(bytes, new byte[0], DataProtectionScope.LocalMachine);
return System.Text.Encoding.UTF8.GetString(encBytes);
}
catch (Exception ex)
{
return String.Empty;
}
}
At other Page , use like.........
var decryptedString=Decrypt(Request["YOUR PASSING ID"] || Request.QueryString["YOUR PASSING ID"]));

- 2,371
- 2
- 29
- 58
-
Thank you for your valuable answer. It simplifies my coding to encrypt query string value from grid view selection. – RGS Dec 25 '12 at 18:28
One approach is create a GUID for each ID you want to pass, and keep tracking in a Dictionary somewhere on the back-end. So you pass the Guid in the querystring and 'decode' it with the dictionary back to a normal ID.
However, this is 'security by obscurity' so you still need to perform an authorization check on the receiving page (To make sure nobody fiddles with the querystring. Of course, the chance of guessing a GUID right is probably smaller than being struck by lightning, still you need to check).

- 8,856
- 2
- 30
- 50