Introduction: In this
article I am going to explain with example How to encrypt and decrypt or we can say encode and decode login credentials e.g. username and password and store in Sql Server Database using Asp.net
with both C# and Vb.Net Language.
Description: In
previous article I explained How to Encrypt Query String in asp.net(C#, VB) | Encrypting and Decrypting Query String in asp.net(C#, VB) and How to Encrypt connection string in web.config | How to Decrypt connection string in web.config and Sql server query to get second,third,fourth or nth highest salary of employee and Load more records in Gridview on button click from sql server table and Encrypt and Decrypt connectionString in web.config file using code in asp.net.
Now in this article I will store/save User Name and Password in the Sql Server Database in encrypted form. Also the Encrypted credentials i.e. user Name and Password will be binded in the first Grid View and In the second Grid View decrypted credentials will be binded as shown in the demo image above.
Now in this article I will store/save User Name and Password in the Sql Server Database in encrypted form. Also the Encrypted credentials i.e. user Name and Password will be binded in the first Grid View and In the second Grid View decrypted credentials will be binded as shown in the demo image above.
Implementation: Let’s
create an asp.net web application to understand the concept of encrypting and
decrypting username and password.
- First of all we need to create a DataBase in Sql Server. So create a Database and name it “MyDatabase” or whatever you want. Create a table with the fields and Data type as shown below and name it “Tb_Login”.
Column Name
|
Data Type
|
Id
|
Int(Primary
Key so set is identity=true)
|
Name
|
varchar(100)
|
UserName
|
varchar(100)
|
Password
|
varchar(100)
|
- Now In the web.config file create the connection string to connect the web application with the database as:
<connectionStrings>
<add name="conStr" connectionString="Data
Source=LocalServer;Initial Catalog=MyDataBase;Integrated Security=True"/>
</connectionStrings>
HTML Source Code
- In the <Form> tag of the
design page (.aspx) place 3 TextBox control, a label and Two Button controls from the standard
category of the visual studio’s toolbox, 3 RequiredFieldValidator validation
controls for each textbox from the validation Category, and also place Two
GridView data controls from the Data category and design the page as shown
below.
<fieldset style="width:400px;">
<legend>
Signup form
</legend>
<table>
<tr>
<td>Name: </td><td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox><asp:RequiredFieldValidator
ID="rfvName" runat="server" ErrorMessage="Please enter Name"
ControlToValidate="txtName" Display="Dynamic" ForeColor="Red"
SetFocusOnError="True"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td>User Name: </td><td>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><asp:RequiredFieldValidator
ID="rfvuserName" runat="server"
ErrorMessage="Please enter User Name" ControlToValidate="txtUserName"
Display="Dynamic" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td>Password: </td><td>
<asp:TextBox ID="txtPwd" runat="server" TextMode="Password"></asp:TextBox><asp:RequiredFieldValidator
ID="rfvpwd" runat="server"
ErrorMessage="Please enter
Password" ControlToValidate="txtPwd"
Display="Dynamic" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td> </td><td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click"/>
<asp:Button ID="btnReset" runat="server" Text="Reset" CausesValidation="False"
onclick="btnReset_Click" /></td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblSignUpStatus" runat="server" Text="" style="color: #006600"></asp:Label></td>
</tr>
</table>
</fieldset>
<br />
<fieldset style="width:400px;">
<legend>Encrypted
Credentials in GridView</legend>
<asp:GridView ID="grdEncryptedCredentials" runat="server"
AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333"
GridLines="None" Width="362px">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="User Name" DataField="UserName" />
<asp:BoundField HeaderText="Password" DataField="Password" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
</fieldset>
<br />
<fieldset style="width:400px;">
<legend>Decrypted
Credentials in GridView</legend>
<asp:GridView ID="grdDecryptedCredentials" runat="server"
AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84"
BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2"
Width="369px">
<Columns>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="User Name" DataField="UserName" />
<asp:BoundField HeaderText="Password" DataField="Password" />
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
</fieldset>
</div>
Asp.Net C# Code for encrypting and decrypting username and password and save
in Sql Server Database
- In the code behind file (.aspx.cs) write the code as:
First
include these following namespace also:
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
Then
write the code as:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
protected void Page_Load(object
sender, EventArgs e)
{
if
(!Page.IsPostBack)
{
BindEncryptedCredentials();
BingDecryptedCredentials();
}
}
private void BindEncryptedCredentials()
{
SqlCommand
cmd = new SqlCommand("select * from Tb_Login", con);
try
{
if
(con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataAdapter
adp = new SqlDataAdapter(cmd);
DataTable
dt = new DataTable();
adp.Fill(dt);
if
(dt.Rows.Count > 0)
{
grdEncryptedCredentials.DataSource = dt;
grdEncryptedCredentials.DataBind();
}
else
{
grdEncryptedCredentials.DataSource = null;
grdEncryptedCredentials.DataBind();
}
}
catch (Exception ex)
{
Response.Write("Error occured :" +
ex.Message.ToString());
}
finally
{
cmd.Dispose();
con.Close();
}
}
private void BingDecryptedCredentials()
{
SqlCommand
cmd = new SqlCommand("select * from Tb_Login", con);
try
{
if
(con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataAdapter
adp = new SqlDataAdapter(cmd);
DataTable
dt = new DataTable();
adp.Fill(dt);
if
(dt.Rows.Count > 0)
{
for
( int i = 0; i < dt.Rows.Count; i++)
{
string
uName = dt.Rows[i]["userName"].ToString();
string
pwd = dt.Rows[i]["Password"].ToString();
dt.Rows[i]["userName"]= Decrypt(uName);
dt.Rows[i]["Password"] = Decrypt(pwd);
}
dt.AcceptChanges();
grdDecryptedCredentials.DataSource
= dt;
grdDecryptedCredentials.DataBind();
}
else
{
grdDecryptedCredentials.DataSource = null;
grdDecryptedCredentials.DataBind();
}
}
catch (Exception ex)
{
Response.Write("Error occured :" +
ex.Message.ToString());
}
finally
{
cmd.Dispose();
con.Close();
}
}
protected void btnSubmit_Click(object
sender, EventArgs e)
{
string
uName = string.Empty;
string
uPwd = string.Empty;
SqlCommand
cmd = new SqlCommand("insert into Tb_Login(Name,UserName,Password) values
(@Name,@UserName,@Password)", con);
if
(con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
uName =
Encrypt(txtUserName.Text.Trim());
uPwd = Encrypt(txtPwd.Text.Trim());
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Name", txtName.Text.Trim());
cmd.Parameters.AddWithValue("@UserName", uName);
cmd.Parameters.AddWithValue("@Password", uPwd);
cmd.ExecuteNonQuery();
lblSignUpStatus.Text = "Record Successfully submitted";
Clear_Controls();
BindEncryptedCredentials();
BingDecryptedCredentials();
}
catch (Exception ex)
{
Response.Write("Error occured: " +
ex.Message.ToString());
}
finally
{
uName = string.Empty;
uPwd = string.Empty;
con.Close();
cmd.Dispose();
}
}
public string Encrypt(string
str)
{
string
EncrptKey = "2013;[pnuLIT)WebCodeExpert";
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 string Decrypt(string
str)
{
str = str.Replace(" ", "+");
string
DecryptKey = "2013;[pnuLIT)WebCodeExpert";
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());
}
private void Clear_Controls()
{
txtName.Text = string.Empty;
txtPwd.Text = string.Empty;
txtUserName.Text = string.Empty;
txtName.Focus();
}
protected void btnReset_Click(object
sender, EventArgs e)
{
Clear_Controls();
lblSignUpStatus.Text = string.Empty;
}
Asp.Net VB Code for encrypting and decrypting username and password and save
in Sql Server Database
- In the code behind file(.aspx.vb) write the code as:
First
import these namespaces also:
Imports System.Security.Cryptography
Imports System.IO
Imports System.Text
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Then
write the code as:
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
Protected Sub Page_Load(sender As
Object, e As
System.EventArgs) Handles
Me.Load
If Not Page.IsPostBack Then
BindEncryptedCredentials()
BingDecryptedCredentials()
End If
End Sub
Private Sub BindEncryptedCredentials()
Dim
cmd As New SqlCommand("select
* from Tb_Login", con)
Try
If
con.State = ConnectionState.Closed Then
con.Open()
End
If
Dim
adp As New SqlDataAdapter(cmd)
Dim
dt As New DataTable()
adp.Fill(dt)
If
dt.Rows.Count > 0 Then
grdEncryptedCredentials.DataSource = dt
grdEncryptedCredentials.DataBind()
Else
grdEncryptedCredentials.DataSource = Nothing
grdEncryptedCredentials.DataBind()
End
If
Catch
ex As Exception
Response.Write("Error occured :" &
ex.Message.ToString())
Finally
cmd.Dispose()
con.Close()
End Try
End Sub
Private Sub BingDecryptedCredentials()
Dim cmd
As New SqlCommand("select
* from Tb_Login", con)
Try
If
con.State = ConnectionState.Closed Then
con.Open()
End
If
Dim
adp As New SqlDataAdapter(cmd)
Dim
dt As New DataTable()
adp.Fill(dt)
If
dt.Rows.Count > 0 Then
For
i As Integer =
0 To dt.Rows.Count - 1
Dim
uName As String
= dt.Rows(i)("userName").ToString()
Dim
pwd As String =
dt.Rows(i)("Password").ToString()
dt.Rows(i)("userName") = Decrypt(uName)
dt.Rows(i)("Password") = Decrypt(pwd)
Next
dt.AcceptChanges()
grdDecryptedCredentials.DataSource = dt
grdDecryptedCredentials.DataBind()
Else
grdDecryptedCredentials.DataSource = Nothing
grdDecryptedCredentials.DataBind()
End If
Catch
ex As Exception
Response.Write("Error occured :" &
ex.Message.ToString())
Finally
cmd.Dispose()
con.Close()
End Try
End Sub
Protected Sub btnSubmit_Click(sender As
Object, e As
System.EventArgs) Handles
btnSubmit.Click
Dim
uName As String
= String.Empty
Dim
uPwd As String
= String.Empty
Dim cmd
As New SqlCommand("insert
into Tb_Login(Name,UserName,Password) values (@Name,@UserName,@Password)",
con)
If
con.State = ConnectionState.Closed Then
con.Open()
End If
Try
uName =
Encrypt(txtUserName.Text.Trim())
uPwd = Encrypt(txtPwd.Text.Trim())
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("@Name", txtName.Text.Trim())
cmd.Parameters.AddWithValue("@UserName", uName)
cmd.Parameters.AddWithValue("@Password", uPwd)
cmd.ExecuteNonQuery()
lblSignUpStatus.Text = "Record Successfully submitted"
Clear_Controls()
BindEncryptedCredentials()
BingDecryptedCredentials()
Catch
ex As Exception
Response.Write("Error occured: " &
ex.Message.ToString())
Finally
uName = String.Empty
uPwd = String.Empty
con.Close()
cmd.Dispose()
End Try
End Sub
Public Function Encrypt(str As
String) As String
Dim
EncrptKey As String
= "2013;[pnuLIT)WebCodeExpert"
Dim
byKey As Byte()
= {}
Dim IV As Byte() = {18, 52,
86, 120, 144, 171, _
205, 239}
byKey = System.Text.Encoding.UTF8.GetBytes(EncrptKey.Substring(0, 8))
Dim des
As New DESCryptoServiceProvider()
Dim
inputByteArray As Byte()
= Encoding.UTF8.GetBytes(str)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0,
inputByteArray.Length)
cs.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray())
End Function
Public Function Decrypt(str As
String) As String
str = str.Replace(" ", "+")
Dim
DecryptKey As String
= "2013;[pnuLIT)WebCodeExpert"
Dim
byKey As Byte()
= {}
Dim IV As Byte() = {18, 52,
86, 120, 144, 171, _
205, 239}
Dim
inputByteArray As Byte()
= New Byte(str.Length
- 1) {}
byKey = System.Text.Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8))
Dim des
As New DESCryptoServiceProvider()
inputByteArray = Convert.FromBase64String(str.Replace(" ", "+"))
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0,
inputByteArray.Length)
cs.FlushFinalBlock()
Dim
encoding As System.Text.Encoding = System.Text.Encoding.UTF8
Return encoding.GetString(ms.ToArray())
End Function
Private Sub Clear_Controls()
txtName.Text = String.Empty
txtPwd.Text = String.Empty
txtUserName.Text = String.Empty
txtName.Focus()
End Sub
Protected Sub btnReset_Click(sender As
Object, e As
System.EventArgs) Handles
btnReset.Click
Clear_Controls()
lblSignUpStatus.Text = String.Empty
End Sub
Now
run the application and enter Name, Username and password and click on
submit. User Name and password will be
stored in the Sql Server Database in encrypted form. Encrypted credentials i.e.
user Name and Password is binded in the first Grid View and In the second Grid View decrypted
credentials are binded.
Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates."
Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates."
12 comments
Click here for commentsfind error :Invalid length for a Base-64 char array or string
Replyin
inputByteArray = Convert.FromBase64String(str.Replace(" ", "+"));
Please share the created code sample for VB.net
Replysir this Error occured :Invalid length for a Base-64 char array.
ReplyIn Decrypt funcition ...
Hi, This code is completely working and tested. Are you trying the same article or modifying as per your requirement?
ReplyHi Rohit Kumar, This code is completely working and tested. Are you trying the same article or modifying as per your requirement?let me know i will help you sort out your error..
Replysir why are u replace string "" with +
Replyjust codes no walk through on Salt, IVs ?? why DES as specific cryptoservice provider??
ReplyHi, I was wondering why you use encrypting instead of hashed passwords? Many thanks
ReplyHi, there are multiple ways for that purpose..encrypting was also one of them,,:)
Replywowwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
ReplyThanks for your valuable feedback..
ReplyI Am new learner of C#.net and I wanted to know detailed working of the code.. Specially In Encrypt and Decrypt function only... Can u help me sir
ReplyIf you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..