In this article I will explain with an example, how to encrypt and store Username or Password in SQL Server database table and then fetch, decrypt and display it in ASP.Net using C# and VB.Net.
The Username or Password will be first encrypted using Symmetric (Same) key AES Algorithm and then will be stored in the database.
The Decryption will be done by fetching the encrypted Username or Password from Database and then decrypting it using the same key that was used for encryption.
Database
I have created a new database named UsersDB which consist of one table named Users with the following schema.
The Password column has been defined as NVARCHAR type, so that it can easily store encrypted password containing special characters.
Note: You can download the database table SQL by clicking the download link below.
Download SQL file
HTML Markup
The following HTML Markup consists of two TextBoxes, a Button and a GridView control.
The Password TextBox has been set with TextMode property as Password.
The GridView has been assigned OnRowDataBound event handler.
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Username:</td>
<td><asp:TextBox ID="txtUsername" runat="server" /></td>
</tr>
<tr>
<td>Password:</td>
<td><asp:TextBox ID="txtPassword" runat="server" TextMode="Password" /></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="Submit" /></td>
</tr>
</table>
<hr/>
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField DataField="Username" HeaderText="Username" />
<asp:BoundField DataField="Password" HeaderText="Encrypted Password" />
<asp:BoundField DataField="Password" HeaderText="Decrypted Password" />
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Security.Cryptography;
VB.Net
Imports System.IO
Imports System.Text
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Security.Cryptography
AES Algorithm Encryption and Decryption functions
The following functions Encrypt and Decrypt will be used to perform encryption and decryption.
C#
private string Encrypt(string clearText)
{
string encryptionKey = "MAKV2SPBNI99212";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(encryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
private string Decrypt(string cipherText)
{
string encryptionKey = "MAKV2SPBNI99212";
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(encryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
VB.Net
Private Function Encrypt(clearText As String) As String
Dim encryptionKey As String = "MAKV2SPBNI99212"
Dim clearBytes As Byte() = Encoding.Unicode.GetBytes(clearText)
Using encryptor As Aes = Aes.Create()
Dim pdb As New Rfc2898DeriveBytes(encryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _
&H65, &H64, &H76, &H65, &H64, &H65, H76})
encryptor.Key = pdb.GetBytes(32)
encryptor.IV = pdb.GetBytes(16)
Using ms As New MemoryStream()
Using cs As New CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)
cs.Write(clearBytes, 0, clearBytes.Length)
cs.Close()
End Using
clearText = Convert.ToBase64String(ms.ToArray())
End Using
End Using
Return clearText
End Function
Private Function Decrypt(cipherText As String) As String
Dim encryptionKey As String = "MAKV2SPBNI99212"
Dim cipherBytes As Byte() = Convert.FromBase64String(cipherText)
Using encryptor As Aes = Aes.Create()
Dim pdb As New Rfc2898DeriveBytes(encryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _
&H65, &H64, &H76, &H65, &H64, &H65, &H76})
encryptor.Key = pdb.GetBytes(32)
encryptor.IV = pdb.GetBytes(16)
Using ms As New MemoryStream()
Using cs As New CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)
cs.Write(cipherBytes, 0, cipherBytes.Length)
cs.Close()
End Using
cipherText = Encoding.Unicode.GetString(ms.ToArray())
End Using
End Using
Return cipherText
End Function
Encrypting and storing the Password in Database Table
When the Submit Button is clicked, the Username and Password will be inserted into the SQL Server database table.
The Username is inserted directly but the Password is first encrypted using the Encrypt function (discussed earlier) and then it is inserted.
C#
protected void Submit(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Users VALUES(@Username, @Password)"))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim());
cmd.Parameters.AddWithValue("@Password", this.Encrypt(txtPassword.Text.Trim()));
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("INSERT INTO Users VALUES(@Username, @Password)")
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim())
cmd.Parameters.AddWithValue("@Password", Me.Encrypt(txtPassword.Text.Trim()))
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
Response.Redirect(Request.Url.AbsoluteUri)
End Sub
Displaying the Usernames and the Encrypted and Decrypted Passwords
Inside the Page Load event, the GridView control is populated with the records from the Users table.
Then inside the OnRowDataBound event handler, the encrypted Password is fetched and decrypted using the Decrypt function (discussed earlier).
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gvUsers.DataSource = dt;
gvUsers.DataBind();
}
}
}
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[2].Text = this.Decrypt(e.Row.Cells[2].Text);
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("SELECT * FROM Users")
Using sda As New SqlDataAdapter()
Dim dt As New DataTable()
cmd.CommandType = CommandType.Text
cmd.Connection = con
sda.SelectCommand = cmd
sda.Fill(dt)
gvUsers.DataSource = dt
gvUsers.DataBind()
End Using
End Using
End Using
End If
End Sub
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Cells(2).Text = Me.Decrypt(e.Row.Cells(2).Text)
End If
End Sub
Screenshot
Downloads