How to: 2.0 Encrypting Field Data Using a Formview Control and a Gridview control for SQL

The Exercise:

Using a Formview Control and a Gridview control to Encrypt data going into SQL, Decrypt it for display, and Be able to Edit it. Using Visual Studio 2005 ASP.NET 2.0 Framework


Files needed: –

  • QSEnc64.vb to be placed in the App_Code folder of your application
  • TestInsertEdit.aspx in the root of the application
  • TestInsertEdit.aspx.vb in the root of the application
  • A Web Config file with a valid ConnectionString Your_SQLConnectionString
  • A SQL Database that you can add the test table to (see script below)


Hopefully this exercise will save you the time it took me to figure it out and you will be able to adapt it to your application. If you have better ideas or useful mods, post them please!


The following is the Class file for QSEnc64.vb

(Originally written by Tiberus Osburn


Imports System

Imports System.IO

Imports System.Xml

Imports System.Text

Imports System.Security.Cryptography


Public Class Encryption64

    Private key() As Byte = {}

    Private IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}


    Public Function Decrypt(ByVal stringToDecrypt As String, _

        ByVal sEncryptionKey As String) As String

        Dim inputByteArray(stringToDecrypt.Length) As Byte


            key = System.Text.Encoding.UTF8.GetBytes(Left(sEncryptionKey, 8))

            Dim des As New DESCryptoServiceProvider()

            inputByteArray = Convert.FromBase64String(stringToDecrypt)

            Dim ms As New MemoryStream()

            Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), _


            cs.Write(inputByteArray, 0, inputByteArray.Length)


            Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8

            Return encoding.GetString(ms.ToArray())

        Catch e As Exception

            Return e.Message

        End Try

    End Function


    Public Function Encrypt(ByVal stringToEncrypt As String, _

        ByVal SEncryptionKey As String) As String


            key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8))

            Dim des As New DESCryptoServiceProvider()

            Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes( _


            Dim ms As New MemoryStream()

            Dim cs As New CryptoStream(ms, des.CreateEncryptor(key, IV), _


            cs.Write(inputByteArray, 0, inputByteArray.Length)


            Return Convert.ToBase64String(ms.ToArray())

        Catch e As Exception

            Return e.Message

        End Try

    End Function


End Class



The following is the aspx page code for TestInsertEdit.aspx


<%@ Page Language="VB" AutoEventWireup="false" CodeFile="TestInsertEdit.aspx.vb" Inherits="TestInsertEdit" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">


<html xmlns="" >

<head runat="server">

    <title>Testing an Encrypted Insert</title>



    <form id="form1" runat="server">


        <asp:Button ID="Button2" runat="server" Text="Insert Mode" PostBackUrl="~/TestInsertEdit.aspx" />

        <asp:Button ID="Button1" runat="server" Text="Edit Mode" PostBackUrl="~/TestInsertEdit.aspx" />

        <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>

        <br />

        <br />

        <asp:FormView ID="FormView1" runat="server" DataKeyNames="testID" DataSourceID="SqlDataTest"




                <asp:Label ID="testIDLabel1" runat="server" Text='<%# Eval("testID") %>'></asp:Label><br />


                <asp:TextBox ID="testItemTextBox" runat="server" Text='<%# useDecrypt(Eval("testItem")) %>'></asp:TextBox>

                <br />

                2<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("testItem") %>'></asp:TextBox><br />

                <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update"

                    OnClick="UpdateButton_Click" Text="Update"></asp:LinkButton>

                <asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"





                <asp:TextBox ID="testItemTextBox" runat="server" Text='<%# Bind("testItem") %>'>

                </asp:TextBox><br />

                <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert"



                <asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"






                <asp:Label ID="testIDLabel" runat="server" Text='<%# Eval("testID") %>'></asp:Label><br />


                <asp:Label ID="testItemLabel" runat="server" Text='<%# Bind("testItem") %>'></asp:Label><br />



        <asp:SqlDataSource ID="SqlDataTest" runat="server" ConnectionString="<%$ ConnectionStrings:Your_SQLConnectionString %>"

            InsertCommand="spTestInsert" InsertCommandType="StoredProcedure" SelectCommand="SELECT * FROM [tblTest]"

            UpdateCommand="spTestUpdate" UpdateCommandType="StoredProcedure">


                <asp:Parameter Name="testItem" Type="String" />

                <asp:Parameter Name="testID" Type="Int32" />

                <asp:Parameter Direction="ReturnValue" Name="RETURN_VALUE" Type="Int32" />



                <asp:Parameter Name="testItem" Type="String" />

                <asp:Parameter Direction="ReturnValue" Name="RETURN_VALUE" Type="Int32" />



        <br />

        ___________________________________________<br />


        <br />

        <br />

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="testID"



                <asp:BoundField DataField="testID" HeaderText="testID" InsertVisible="False" ReadOnly="True"

                    SortExpression="testID" />

                <asp:TemplateField HeaderText="testItem" SortExpression="testItem">


                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("testItem") %>'></asp:TextBox>



                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("testItem") %>'></asp:Label>

                        <br />

                        <asp:Label ID="Label2" runat="server" Text='<%# useDecrypt(Eval("testItem")) %>'></asp:Label>











The following is the CodeBehind TestInsertEdit.vb



Partial Class TestInsertEdit

    Inherits System.Web.UI.Page

    'What does this all mean? by Tyrus

    'This page is an experiment to figure out how to Insert, View, and Edit a Value

    'that needs to be encrypted in the database.

    'This page uses QSEnc64.vb from

    'Some slight modifications should be made to the class to increase security. i.e. Changing the private KEY called IV

    'OK so on to the good stuff


    'This Method catches the value being inserted and encrypts it with the Encryption64 Class

    'as it is being inserted into the database

    Protected Sub FormView1_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertEventArgs) Handles FormView1.ItemInserting

        Dim Enc64 As New Encryption64

        Dim NewText As String = Enc64.Encrypt(e.Values.Item(0).ToString, "1234R%66#5R")

        e.Values.Item(0) = NewText

    End Sub


    'This method is used by the label in the formview. When the formview loads the DataBinding

    'or more correctly the Eval statement of the label showing the decrypted field looks like

    'useDecrypt(Eval("foo")) which calls this method

    'which in turn uses the Encryption64 class to Decrypt the string coming out of the database

    Function useDecrypt(ByVal vText As String)

        Dim Enc64 As New Encryption64

        Dim vKey As String = "1234R%66#5R"

        Dim vDecryptedText As String = Enc64.Decrypt(vText, vKey).ToString

        Return vDecryptedText

    End Function


    'Finally I needed to do something tricky to get a new value from an edit Reencrypted

    'Since Bind is not valid if you use it like Enc64.Encrypt(Bind("foo"))

    'I had to do it with 2 fields. In this case textboxes, but one would need to be a

    'hidden field in a real scenario. The Key can be whatever you like.

    Protected Sub UpdateButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim Enc64 As New Encryption64

        Dim vKey As String = "1234R%66#5R"

        Dim Txt1 As TextBox = CType(FormView1.FindControl("testItemTextbox"), TextBox)

        Dim Txt2 As TextBox = CType(FormView1.FindControl("textbox2"), TextBox)

        Txt2.Text = Enc64.Encrypt(Txt1.Text, vKey).ToString


    End Sub



    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click


    End Sub


    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click


    End Sub


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Not Page.IsPostBack Then

            If Request.QueryString("formMode") = "Insert" Then

                FormView1.DefaultMode = FormViewMode.Insert

            ElseIf Request.QueryString("formMode") = "Edit" Then

                FormView1.DefaultMode = FormViewMode.Edit



            End If

        End If

        If Not Request.QueryString("formMode") Is Nothing Then

            Label3.Text = Request.QueryString("formMode").ToString


            Label3.Text = "Mode not chosen. Using Default."

        End If

    End Sub

End Class



The following is the SQL Script for the Test Table


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tblTest]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)

drop table [dbo].[tblTest]



CREATE TABLE [dbo].[tblTest] (

            [testID] [int] IDENTITY (1, 1) NOT NULL ,

            [testItem] [nvarchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL




"nothing" really matters!
2/10/2006 4:03:27 PM 91979 articles. 4 followers. Follow

0 Replies

Similar Articles

[PageSpeed] 55


Similar Artilces:

Trying to use the FAQ " Sorting and paging in the GridView control when not using data source controls "Sorting and paging in the GridView control when not using..."
and I am not getting the results I had hoped for.  I keep getting a "Compiler Error Message: CS0123: No overload for 'AdhocJobGridView_PageIndexChanged' matches delegate 'System.EventHandler'".   Here is my event handling... protected void AdhocJobGridView_PageIndexChanged(object sender, GridViewPageEventArgs e){ try { AdhocJobGridView.DataSource = wsBaseInfoArray; AdhocJobGridView.PageIndex = e.NewPageIndex; AdhocJobGridView.DataBind(); }catch (Exception ex) {throw ex; }   Here is my aspx... <asp:GridView ID="AdhocJobGridView...

Datagrid(.net 1.1) to GridView(.net 2.0) and using the RowUpdating event how to extract the values from the controls.
Ok  This is the settings: I use a Viewgrid with only itemtemplate colums for example. <asp:TemplateField HeaderText="Test"><ItemTemplate><asp:Label id="LBL_Test" text='<%# DataBinder.Eval(Container.DataItem, "Test1") %>' runat="server" meta:resourcekey="LBL_TestResource1"></asp:Label></font></ItemTemplate> <EditItemTemplate><asp:TextBox ID="HDN_Test" Text='<%# DataBinder.Eval(Container.DataItem, "Test1") %>' Runat="server" meta:resourcekey="HDN_TestResource1" /></EditItemTemplate></asp:TemplateField>  The ...

Where the data get stored in Wizard control. .NET 2.0
Can somebody please let me know that... Where the data get stored when we use Wizard control in .NET 2.0. Is it stores data in viewstate or use some hidden variable??   Data are stored in ViewState and ViewState is stored in hidden field by default. Note, than you can change place where ViewState is stored. You can implement your custom ViewState handling mechanism creating subclass from System.Web.UI.PageStatePersister class. ASP.NET 2.0 contains two implementations:     System.Web.UI.HiddenFieldPageStatePersister    System.Web.U...

Question on getting data from my db without using a control like gridview, formview, etc.
Right now I have a lead db, which starts with a gridview of all the leads, filtered by name, type, etc. Clicking details on each row, passes the info to a editable formview. I want to have a button that will email that lead, on the same page. What is the easiest way to pass the a column value to the method I'll be creating? I.e. send to: emailaddress(pulled from the formview field for that lead). Or even better how could I just query the db, and then pass that value on to the email method?  I know its a stupid question, Im brand new to have little background in C# and php. ...

need code for updating gridview in .NET 2.0 without using sql data source
hi,this is satish,I have faced problem to update the gridview with template columns in .NET 2.0 without using sql datasource.So please send me the code with events for updating gridview with teplate columns including one dropdownlist inatead of textbox without using sql data source.i hope you will understand my question, please send the answer ASAP.Waiting for reply,regards You will need to deal with it as if it was a traditional GridView in ASP.NET 1.x. Hope this helps! Hammoudeh AhmadWE never know how high we are ... Till we are called to rise And then, if we are true to...

Issue with getting values from child controls in a gridview, to use for the update using a SQLDataSource control
Hi all, I have a gridview bound with a SQLDataSource. I am using the Update feature of the SQLDataSource to update a SQL Server database with values entered into the gridview. However I am not getting it to work. I believe this is due to the controls that contain the user entries are not the gridview itself, but rather child controls within the gridview. I have been using the names of the actual controls but nothing happens. Upon submit, the screen returns blank, and the database is not updated. Here is some code:   <asp:GridView ID="GridEditSettlement" runat="server" AutoGenerate...

how to get a control ID from a bind field name / bound field (column) name from a formview's control
I have a form view which is bound to a table, now from codebehind file I need to apply some formatting based on some of the field's bound control. For example, if Formview1 is bound to Employee table, and it's item template has a control with ID "Label1" which is bound to "EmployeeJoinDate" . Now, I have a different table which has a list of field name(EmployeeJoinDate is one of them), all of which should be applied some formatting based on some condition. Now I can take two approach for that, but I am stuck at both:  1. If I can somehow get the contro...

Getting the control id of a control inside gridview control
 uhmm.. a little bit confusing regarding my subject because i dont know how to say the way my problem is how can i get the id of a control (e.g. textbox) inside the gridview... and the textbox is in the templatefield... is there any way i can get its id??  hoping i could get a reply as soon as possible... Regards,MhaeyPlease remember to click “Mark as Answer” on the post that helps you.. =) What do you want's to do by getting the id of the Text box? Do you want's to find particular Textbox with certain id ? Kamran ShahidSr. Software Engineer(MCP,,MC...

Data Controls in .Net 2.0
What is the difference between GridView, DataLis, DetailsView & FormView.  Thanks & Regards Jai Shankar Here is how I  understand them. 1. Gridview displays multiple lists of data, and it supports paging, sorting, among other things2. DataList is pretty much the same, but you have more control over the html you generate over the gridview, but you won't get paging and sorting right out of the box. 3. DetailsView display one record (meaning one of the row in a gridview). Also, I believe you have limited control over the html it generates4. FormsView is just like detail...

.net 2.0 data controls
I've just begun taking a look at .net 2.0 and am unsure if the new Data Controls will help with this problem.  I have a column in my database that stores a pdf filename, ex:  "pdfSample.pdf".  The directory is a variable within my project.  In my GridView, I need code that does the following: Private Sub ProductDetails_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles productdetail.RowDataBound&nbsp; Dim img As Image = CType(e.Row.FindControl("pdfImage"), Image) &nbsp; Dim pdfURL As String = "" 'Get the &qu...

Using Data Control in another data control
Hey, How to use a SqlDataSource control in a GridView and so on...I mean i wanna show data which comes from UserTables in a gridview whoses data comes from ContentTable so they are two separated tables. Thanks and Regards...I am not a perfect programmer, but i have perfect programmers' habits [ i think so :)] I mean how to use nested gridview controls. Please aren't there any poeple who can help me ?I am not a perfect programmer, but i have perfect programmers' habits [ i think so :)] Try the links below, they might be of some help to you.http://msdn2.microso...

Master Details in two seperate GridView Controls
I am simply trying to have a list of people in the top grid control (works fine), then when selected have the second Grid Control show details for that person(not working). Here is what I am trying from the load event: Sub BindData() Dim myConnection As New MySql.Data.MySqlClient.MySqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionSql")) Dim strPersonSQL, strActSQL As String strPersonSQL = "select row_id, first_name, last_name, middle_initial, dsi_id, created, created_by, program_of_study, email from tbl_person" Dim myPerCommand As New MySqlClient.MySqlComm...

(master/detail) control using gridview and formview controls problem...
hi guys, i'm new to .net programming and have been toying with the (master/detail) control using gridview and formview controls...however, i can't seem to drilldown to the correct record when the primary key is a composite key. please help....   <asp:GridView ID="GridView1" runat="server" DataKeyNames="ServiceID,VersionNum" CellPadding="4" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None"               &nbs...

How to validate controls on a .NET 2.0 Web user Control
Hi Guys, (ASP.NET 2.0 / C#) I've looked thorugh every post on validating web user controls (and know about Pter Blum's Professional Validation and More package) - but can't seem to get my head around whre to start. I have a web user control, called wucICL.ascx on a we page called AddEditInvestment.aspx.  I would like to validate a couple of DropDownLists (ddlAccounts and ddlContacts) when the Insert and Update buttons are clicked on the AddEdit Investment page. The other controls on the AddEditInvestments page belong to a validation group called All Validators and the DropDownL...

Web resources about - How to: 2.0 Encrypting Field Data Using a Formview Control and a Gridview control for SQL -

Encrypting File System - Wikipedia, the free encyclopedia
By default, no files are encrypted, but encryption can be enabled by users on a per-file, per-directory, or per-drive basis. Some EFS settings ...

Encrypting data within Perzo - David Gurle CEO and Founder of Perzo - ITProPortal - YouTube
For more videos and related content visit: ITProPortal spoke to encryption guru David Gurle about the future of internet ...

Stung by file-encrypting malware, researchers fight back
Jose Vildoza's 62-year-old father was using his old Windows computer when a warning in broken English flashed on the screen: your files have ...

Cybercrooks developing dangerous new file-encrypting ransomware, researchers warn
A team of malware developers is preparing to sell a new ransomware program that encrypts files on infected computers and asks victims for money ...

Hackers shakedown businesses by encrypting their websites
Crypto-ransomware hackers who have plagued PCs for the past two years have found a new tack — high value business websites.

iPhone gets first free app for encrypting voice calls
An open-source project has released the first free application for the iPhone that scrambles voice calls, which would thwart government surveillance ...

Apple not encrypting email attachments in iOS 7, security researcher claims
Apple's Mail app in iOS 7 is failing to encrypt email attachments, leaving user data vulnerable to hackers, a security researcher claims.

Apple could be forced to stop completely encrypting iPhones and services under UK law
... data behind a password — encryption that Apple can’t break through — and government officials wanting access in instances where de-encrypting ...

Comcast Is Encrypting Basic Cable Now
Comcast has decided to start encrypting its basic cable signal. If you have a cable box, this will mean absolutely nothing to you, but if you ...

Resources last updated: 11/25/2015 1:24:46 PM