8 - Easy Steps to encrypt decrypt user data in C#

Data Encryption And Decryption in C#

Dear friends, In previous article you was learn

What is Page.IsValid and page.validate in asp.net?

Difference between dataset and datatable in C-Sharp

How to encrypt decrypt data in C#?

Here you will learn, encrypt and decrypt login credentials e.g. username and password and store in Sql Server Database using Asp.net with C# Language with an simple example.

Here will store (save) UserName and Password return by user from input form into the SQL Server Database in encrypted form.

After save we will bind UserName and Password in first Grid View as it is (encrypted) and In the second Grid View decrypted as explained step by step in example below.

Step 1:   Create DATABASE, SCHEMA, TABLE and Stored Procedures as follows.

We will create database, an schema and a table to store User Credentials.

--Create Database CREATE DATABASE SWCLASSDB Go --Select Working Database USE SWCLASSDB Go --Create Schema CREATE SCHEMA WISH Go --Create User Table CREATE TABLE WISH.tbUsers ( USERID INT CONSTRAINT PK_USERID PRIMARY KEY IDENTITY(1,1), NAME NVARCHAR(200) NOT NULL, USERNAME NVARCHAR(200) CONSTRAINT UQ_USERNAME UNIQUE NOT NULL, USERPASSWORD NVARCHAR(200) NOT NULL ) Go --Create Stored Procedure for Save User Credentials CREATE PROCEDURE WISH.USPUsers_Save ( @NAME NVARCHAR(200), @USERNAME NVARCHAR(200), @USERPASSWORD NVARCHAR(200) ) AS BEGIN INSERT INTO WISH.tbUsers(NAME,USERNAME,USERPASSWORD) VALUES(@NAME,@USERNAME,@USERPASSWORD) IF @@ERROR>0 return 0 ELSE return 1 END Go --Create Stored Procedure to Fetch all Data from User Table CREATE PROCEDURE WISH.USPUsers_SelectAll AS BEGIN SET NOCOUNT ON; SELECT USERID,NAME,USERNAME,USERPASSWORD FROM WISH.tbUsers END Go

Step 2:   Create Web Application using dot net framework.

Step 3:   Add a new Web Form name it UserRegistration.aspx

Step 4:   Create asp.net controls for Registration of new user with validation controls as follows.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserRegistration.aspx.cs" Inherits="DateTimeFormatApp.UserLogin" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">     <title></title> </head> <body>     <form id="form1" runat="server">          <div>             <p><label>Name <span style="color:red">*</span></label><asp:RequiredFieldValidator ID="rfvName" runat="server"                         ControlToValidate="txtName" ErrorMessage=" is required" ValidationGroup="vgLogin"                         ForeColor="#FF3300" SetFocusOnError="True"></asp:RequiredFieldValidator></p>             <asp:TextBox ID="txtName" ValidationGroup="vgLogin"  runat="server"></asp:TextBox>         </div>         <div>             <p><label>User Name <span style="color:red">*</span></label><asp:RequiredFieldValidator ID="rfvUserName" runat="server"                         ControlToValidate="txtUserName" ErrorMessage=" is required" ValidationGroup="vgLogin"                         ForeColor="#FF3300" SetFocusOnError="True"></asp:RequiredFieldValidator></p>             <asp:TextBox ID="txtUserName" ValidationGroup="vgLogin"  runat="server"></asp:TextBox>         </div>          <div>             <p><label>Password <span style="color:red">*</span></label>                                   <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"                         ControlToValidate="txtPassword" ErrorMessage=" is required" ValidationGroup="vgLogin"                         ForeColor="#FF3300" SetFocusOnError="True" Display="Dynamic"></asp:RequiredFieldValidator>                 <asp:CompareValidator ControlToValidate="txtPassword" ID="cvPassword" runat="server"                       ErrorMessage=" is incorrect" ValidationGroup="vgLogin" ForeColor="#FF3300" SetFocusOnError="True" ControlToCompare="txtConfirm" Display="Dynamic"></asp:CompareValidator>             </p>             <asp:TextBox ID="txtPassword" ValidationGroup="vgLogin" TextMode="Password" runat="server"></asp:TextBox>         </div>         <div>             <p><label>Confirmed Password <span style="color:red">*</span></label> <asp:RequiredFieldValidator ID="rfvConfirm" runat="server"                         ControlToValidate="txtConfirm" ErrorMessage=" is required" ValidationGroup="vgLogin"                         ForeColor="#FF3300" SetFocusOnError="True"></asp:RequiredFieldValidator>             </p>             <asp:TextBox ID="txtConfirm" ValidationGroup="vgLogin" TextMode="Password" runat="server"></asp:TextBox>         </div>         <div>             <p><span style="color:red;">&nbsp;<asp:Literal ID="litmsg" runat="server"></asp:Literal></span></p>             <asp:Button ID="btnRegister" ValidationGroup="vgLogin" runat="server" Text="Registration" OnClick="btnRegister_Click" />         </div>         <div style="clear:both;"></div>         <br />         <h4>Encrypted Data</h4>         <div>             <asp:GridView ID="grdEncryptUser" runat="server"></asp:GridView>         </div>         <br />         <h4>Decrypted Data</h4>          <div>             <asp:GridView ID="grdDecryptUser" runat="server"></asp:GridView>         </div>     </form> </body> </html>

Step 5:   Add a new Directory (Folder) naming Services in Solution Explorer. Add a new class file by right click on Services folder with name SWClassCrypto.cs and open it.

Add following Namescpaces in Namespace block on the top of CustomCrypto.cs class file.

 

using System.Security.Cryptography; using System.IO; using System.Text;

Copy following code for CustomCrypto.cs

using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace SWCLASS { public class SWClassCrypto { public static string Encrypt(string str) { string EncrptKey = "@#03swclassswclass2019"; byte[] byKey = { }; byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 }; byKey = System.Text.Encoding.UTF8.GetBytes(EncrptKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.UTF8.GetBytes(str); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Convert.ToBase64String(ms.ToArray()); } public static string Decrypt(string str) { str = str.Replace(" ", "+"); string DecryptKey = "@#03swclassswclass2019"; byte[] byKey = { }; byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 }; byte[] inputByteArray = new byte[str.Length]; byKey = System.Text.Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(str.Replace(" ", "+")); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = System.Text.Encoding.UTF8; return encoding.GetString(ms.ToArray()); } } }

Step 6:   Under services folder add new class with name DTOUser.cs for User Entity Data Transfer Object as follows.

namespace SWCLASS { public class DTOUser { public int UserID { get; set; } public string Name { get; set; } public string UserName { get; set; } public string UserPassword { get; set; } } }

Step 7:  Under services folder add new class with name DALUser.cs for Data Access Layer with two static methods one for Registering New User and Another to get list of all existing Users as follows.

using System; using System.Data; using System.Data.SqlClient; namespace SWCLASS { public class DALUser { public static Tuple RegisterUser(DTOUser obj) { int response = 1; string msg = string.Empty; SqlConnection con = new SqlConnection("data source=DESKTOP-Q3N3A9C;initial catalog=SWCLASSDB;persist security info=True;user id=sa;password=vishal;"); if (con.State == System.Data.ConnectionState.Closed) con.Open(); SqlCommand cmd = new SqlCommand("WISH.USPUsers_Save", con); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@NAME", obj.Name); cmd.Parameters.AddWithValue("@USERNAME", obj.UserName); cmd.Parameters.AddWithValue("@USERPASSWORD", obj.UserPassword); try { response = cmd.ExecuteNonQuery(); } catch (Exception ex) { msg = ex.Message; } finally { cmd.Dispose(); if (con.State == System.Data.ConnectionState.Open) con.Close(); } return Tuple.Create(response, msg); } public static DataTable GetAllRegisteredUsers() { SqlConnection con = new SqlConnection("data source=DESKTOP-Q3N3A9C;initial catalog=SWCLASSDB;persist security info=True;user id=sa;password=vishal;"); DataTable dt; SqlCommand cmd = new SqlCommand("WISH.USPUsers_SelectAll", con); cmd.CommandType = CommandType.StoredProcedure; try { if (con.State == System.Data.ConnectionState.Closed) con.Open(); dt = new DataTable(); SqlDataAdapter adp = new SqlDataAdapter(cmd); adp.Fill(dt); } catch (Exception) { throw; } finally { cmd.Dispose(); if (con.State == System.Data.ConnectionState.Open) con.Close(); } return dt; } } }

Step 8:   Open UserRegistration.aspx form by double click on it from solution explorer and press F7 to open code behind UserRegistration.aspx.cs file.

using SWCLASS; using System; using System.Data; namespace DateTimeFormatApp { public partial class UserLogin : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) { BindUserEncryptedGrid(); BindUserDecryptedGrid(); } } protected void btnRegister_Click(object sender, EventArgs e) { if (!IsValid) return; Tuple t; DTOUser obj = new DTOUser(); obj.Name = txtName.Text.Trim(); obj.UserName = SWClassCrypto.Encrypt(txtUserName.Text.Trim()); obj.UserPassword = SWClassCrypto.Encrypt(txtPassword.Text); t = DALUser.RegisterUser(obj); if (t.Item1==1) { txtUserName.Text = txtPassword.Text = string.Empty; BindUserEncryptedGrid(); litmsg.Text = "User is registered successfully."; } else litmsg.Text = "Failed to register user. " + t.Item2; obj = null; } public void BindUserEncryptedGrid() { DataTable dt = new DataTable(); dt = DALUser.GetAllRegisteredUsers(); if (dt != null) if (dt.Rows.Count > 0) { grdEncryptUser.DataSource = dt; grdEncryptUser.DataBind(); } } public void BindUserDecryptedGrid() { DataTable dt = new DataTable(); dt = DALUser.GetAllRegisteredUsers(); if(dt!=null) if(dt.Rows.Count>0) { foreach(DataRow dr in dt.Rows) { dr[2] = SWClassCrypto.Decrypt(dr[2].ToString()); dr[3] = SWClassCrypto.Decrypt(dr[3].ToString()); } } grdDecryptUser.DataSource = dt; grdDecryptUser.DataBind(); } } }

Here in above UserRegistration.aspx.cs file we created two methods for bind two gridviewss one (grdEncryptUser) with encrypted data stored in database using BindUserEncryptedGrid() Method and another for fetching encrypted data from database and then decrypt before display in gridview control grdDecryptUser by invoking BindUserDecryptedGrid() Method.

Both methods called on page load event.

When user hit Register button with user credentials, btnRegister_Click event raised, which calls RegisterUser() static method of DALUser class to store data into database after encryption by using Encrypt() method of SWClassCrypto class.

Data Encryption And Decryption in C#- Now you know logic for encryption and decryption in this simple example, now you can modified given logic and implement it into your code, not only for user credentials like in above example, you can use same logic for user sensitive data like payment gateway too.

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories