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 Windows Forms (WinForms) Application using C# and VB.Net.
The Username or Password will be first encrypted using AES Symmetric key (Same key) 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.
Encrypt and Decrypt Username or Password stored in database in Windows Application using C# and VB.Net
 
Note:The attached sample contains the SQL Script file to create the database and the table.
 
 
Form Design
The Form Design consists of two TextBoxes, a Button and a DataGridView control.
Encrypt and Decrypt Username or Password stored in database in Windows Application using C# and VB.Net
 
 
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.
Note: The following functions have been explained in the article AES Encryption Decryption (Cryptography) Tutorial with example in ASP.Net using C# and VB.Net.
 
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
 
 
Displaying the Usernames and the Encrypted and Decrypted Passwords
Inside the Form Load event, the DataGridView control is populated with the records from the Users table.
Once the DataTable is populated, a new column is added to the DataTable.
Then a loop is executed over the DataTable rows and the encrypted Password is fetched and decrypted using the Decrypt function (discussed earlier).
C#
private void Form1_Load(object sender, EventArgs e)
{
    PopulateDataGrid();
}
 
private void PopulateDataGrid()
{
    string constr = @"Data Source=.\SQL2017;Initial Catalog=UsersDB;Integrated Security=true";
    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);
                dt.Columns[1].ColumnName = "Encrypted Password";
                dt.Columns.Add("Password");
                foreach (DataRow row in dt.Rows)
                {
                    row["Password"] = Decrypt(row["Encrypted Password"].ToString());
                }
                dgvUsers.DataSource = dt;
            }
        }
    }
}
 
VB.Net
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    PopulateDataGrid()
End Sub
 
Private Sub PopulateDataGrid()
    Dim constr As String = "Data Source=.\SQL2017;Initial Catalog=UsersDB;Integrated Security=true"
    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)
                dgvUsers.DataSource = dt
                dt.Columns(1).ColumnName = "Encrypted Password"
                dt.Columns.Add("Password")
                For Each row As DataRow In dt.Rows
                    row("Password") = Decrypt(row("Encrypted Password").ToString)
                Next
            End Using
        End Using
    End Using
End Sub
 
 
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.
Finally, the DataGridView is again populated by calling the PopulateDataGrid method.
C#
private void btnSubmit_Click(object sender, EventArgs e)
{
    string constr = @"Data Source=.\SQL2017;Initial Catalog=UsersDB;Integrated Security=true";
    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", Encrypt(txtPassword.Text.Trim()));
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
 
    PopulateDataGrid();
}
 
VB.Net
Private Sub btnSubmit_Click(sender As System.Object, e As System.EventArgs) Handles btnSubmit.Click
    Dim constr As String = "Data Source=.\SQL2017;Initial Catalog=UsersDB;Integrated Security=true"
    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", Encrypt(txtPassword.Text.Trim()))
            cmd.Connection = con
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
        End Using
    End Using
 
    PopulateDataGrid()
End Sub
 
 
Screenshots
The encrypted Passwords in SQL Server Database Table
Encrypt and Decrypt Username or Password stored in database in Windows Application using C# and VB.Net
 
The DataGridView displaying both encrypted and decrypted Passwords
Encrypt and Decrypt Username or Password stored in database in Windows Application using C# and VB.Net
 
 
Downloads