Solved

Encrypt and Decrypt GridView Data

Posted on 2010-08-20
18
1,894 Views
Last Modified: 2012-05-10
Hello,

I have the following code below that I need help with. I need to be able to decrypt the data from my database to my GridView control. The decryption does work if I just decrypt to a Label(s) controls but having issues decrypting to GridView control.

HTML Markup:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="retrievedata.aspx.cs" Inherits="retrievedata" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:BoundField DataField="admin_name" HeaderText="Name" />
                <asp:BoundField DataField="admin_address" HeaderText="Name" />
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>


CODEBEHIND:

using EncryptionUtility.APress.ProAspNet.Utility;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class retrievedata : System.Web.UI.Page
{
    private string EncryptionKeyFile;
    protected void Page_Load(object sender, EventArgs e)
    {
        EncryptionKeyFile = Server.MapPath("key.config");
        SymmetricEncryptionUtility.AlgorithmName = "Rijndael";

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admissions"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "Admissions_RetrieveCollectedInfoValues";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        try
        {
            conn.Open();

            SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

            GridView1.DataSource = rdr;
            GridView1.DataBind();

        }

        catch
        {
        }

        finally
        {
            conn.Close();
        }
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.DataItem != null)
        {
            DataRowView dr = (DataRowView)e.Row.DataItem;
            byte[] Address = (byte[])dr["admin_address"];

            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            e.Row.Cells[1].Text = SymmetricEncryptionUtility.DecryptData(Address, EncryptionKeyFile);

        }
    }

}
0
Comment
Question by:asp_net2
  • 12
  • 4
  • 2
18 Comments
 
LVL 20

Expert Comment

by:informaniac
Comment Utility
R u getting any value in Address variable
0
 
LVL 4

Author Comment

by:asp_net2
Comment Utility
yes, when I run the following code above I get the following output below in the image that i'm going to attach.


ee.png
0
 
LVL 4

Author Comment

by:asp_net2
Comment Utility
Hi informaniac,

Just an FYI, the field in the DB that holds the enrypted data is a varbinary field.
0
 
LVL 4

Author Comment

by:asp_net2
Comment Utility
Hi informaniac,

are you still able to assist or are you busy now?
0
 
LVL 12

Expert Comment

by:CmdoProg2
Comment Utility
Assist - I do not use SymmetricEncryptionUtility class, but on mine decryption method need to direct type converson.   Also, I use a templatefield with label/textbox controls.
0
 
LVL 4

Author Comment

by:asp_net2
Comment Utility
can you show me what i'm going wrong then? Or is it different from what I have/use compared to your code?
0
 
LVL 12

Expert Comment

by:CmdoProg2
Comment Utility
try ...
        e.Row.Cells[1].Text = (string)SymmetricEncryptionUtility.DecryptData(Address, EncryptionKeyFile);

in mine (Converted from VB)
      Label lbl = (Label)e.Row.Cells[1].Controls(1); // you may want to use FindControl
      lbl.Text = (string)clsEncryption.Decrypt(boundValue);

from my experience, the text property in a cell does not work the same as a label/textbox text property.  informaniac may be more helpful on the conversion.
0
 
LVL 4

Author Comment

by:asp_net2
Comment Utility
I tried using your code below and the same output is displayed as in post 33484689. Also, the code that I posted is in regards to retrieving data to the GridView not to a Label control. However, I tested the decrpyt code by binding the values to Label controls and the data get decrypted fine, I'm just having trouble decrypting within the GridView.
0
 
LVL 20

Expert Comment

by:informaniac
Comment Utility
Can u just try this if it works?

Put a templatecolumn instead of a boundcolumn and place a label inside the templatecolumn.

And in rowdatabound set the label text to the decrypted data.
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 4

Author Comment

by:asp_net2
Comment Utility
Ok, I added the following below to my HTML page but not sure what to add to my codebehind. Please be specific since I'm a noob at this.

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound" Width="400px">
            <Columns>
                <asp:BoundField DataField="admin_name" HeaderText="Name" />
                <asp:TemplateField><asp:Label ID="Label1" runat="server"></asp:Label></asp:TemplateField>
            </Columns>        
        </asp:GridView>



    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.DataItem != null)
        {
            DataRowView rdr = (DataRowView)e.Row.DataItem;

            byte[] Address = (byte[])rdr["admin_address"];
            e.Row.Cells[1].Text = SymmetricEncryptionUtility.DecryptData(Address, EncryptionKeyFile);

        }
    }
0
 
LVL 20

Accepted Solution

by:
informaniac earned 500 total points
Comment Utility
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      if(e.Row.RowType == DataControlRowType.DataRow)
      {
        if (e.Row.DataItem != null)
        {
            DataRowView rdr = (DataRowView)e.Row.DataItem;

            byte[] Address = (byte[])rdr["admin_address"];
            Label Label1 = (Label)e.Row.FindControl("Label1");
            Label1.Text =  SymmetricEncryptionUtility.DecryptData(Address, EncryptionKeyFile);


        }
      }
    }
0
 
LVL 20

Expert Comment

by:informaniac
Comment Utility
Just being inquisite, how does this line help in ur code

 System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
0
 
LVL 4

Author Comment

by:asp_net2
Comment Utility
I have taken the following line out below that you mention and the effect is still the same.

>> Just being inquisite, how does this line help in ur code
>> System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
0
 
LVL 4

Author Comment

by:asp_net2
Comment Utility
Hi informaniac,

I tried the code that you posted above and when I run it I get the following error message below.

Server Error in '/Admissions' Application.
--------------------------------------------------------------------------------

Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Type 'System.Web.UI.WebControls.TemplateField' does not have a public property named 'Label'.

Source Error:


Line 13:             <Columns>
Line 14:                 <asp:BoundField DataField="admin_name" HeaderText="Name" />
Line 15:                 <asp:TemplateField><asp:Label ID="Label1" runat="server"></asp:Label></asp:TemplateField>
Line 16:             </Columns>        
Line 17:         </asp:GridView>
 

Source File: /Admissions/retrievedata.aspx    Line: 15
0
 
LVL 4

Author Comment

by:asp_net2
Comment Utility
Hi informaniac,

Are you still able to assist? Also, I make changes to the HTML markup which I'm going to post to show you what I have now. When I run the page this time I don't see any error messages but I also don't see the encrypted data either.

HTML MARKUP:

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            OnRowDataBound="GridView1_RowDataBound" Width="400px">
            <Columns>
                <asp:BoundField DataField="admin_name" HeaderText="Name" />
               
                <asp:TemplateField>
                <ItemTemplate><asp:Label ID="Label1" runat="server"></asp:Label></ItemTemplate>
                </asp:TemplateField>
               
            </Columns>    
             
        </asp:GridView>


CODEBEHIND:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.DataItem != null)
            {
                DataRowView rdr = (DataRowView)e.Row.DataItem;

                byte[] Address = (byte[])rdr["admin_address"];
                Label Label1 = (Label)e.Row.FindControl("Label1");
                Label1.Text = SymmetricEncryptionUtility.DecryptData(Address, EncryptionKeyFile);
            }
        }
    }
0
 
LVL 4

Author Comment

by:asp_net2
Comment Utility
Hi informaniac,

Are you still able to help?
0
 
LVL 4

Author Comment

by:asp_net2
Comment Utility
Hello, anyone still able to help?? If not then I plan on grading this post as is which further help by tomorrow morning.
0
 
LVL 4

Author Closing Comment

by:asp_net2
Comment Utility
closing post because it was never followed up with.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now