Encrypt And Decrypt User Password In SQL Server DB Using C# Winform Application

In this article, we are going to learn how to maintain the user login details in SQL server table with password encryption format and decrypt the user password and validate the credentials in the login form.
 
Step 1
 
Create the Database and table to maintain the user login credentials.
 
Here, I have created my database and named it as "LoginDB" and created a table "tblUserRegistration" to maintain the user credentials.
 
Please refer to the below image for your reference.
 
 
Note

The table "tblUserRegistration" has three columns - Id, UserName, Password. Id is a primary key; set its identification to yes and initialize  starting value  as1. UserName and Password are string values, so I set these as varchar datatype.
 
Step 2
 
Let's create a simple Windows application in Visual Studio.
 
To create a Windows application, open Visual Studio and go to New Project. A new dialog window will appear.; Click C# in the left pane and select Windows Form Application there. Name your project and click OK.
 
Here, I have created my project and named it as "EncryptionandDecryption". Now, we will design our user registration form for registering new user credentials.
 
 
Step 3
 
Now, let's create a simple class file in our project to write encryption and decryption logic.To add a class file, right click your project -> Add -> New item -> select class in the dialog box and name your class file. Click OK.
 
Here, I have created my class file and named it as "Cryptography". Now, we can write our encryption and decryption logic.
 
Please find the below code for your reference. 
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text;    
  5. using System.Security.Cryptography;    
  6. using System.IO;    
  7.     
  8. namespace EncryptionandDecryption    
  9. {    
  10.     public class Cryptography    
  11.     {    
  12.         public static string Encrypt(string encryptString)    
  13.         {    
  14.             string EncryptionKey = "0ram@1234xxxxxxxxxxtttttuuuuuiiiiio";  //we can change the code converstion key as per our requirement    
  15.             byte[] clearBytes = Encoding.Unicode.GetBytes(encryptString);    
  16.             using (Aes encryptor = Aes.Create())    
  17.             {    
  18.                 Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {      
  19.             0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76      
  20.         });    
  21.                 encryptor.Key = pdb.GetBytes(32);    
  22.                 encryptor.IV = pdb.GetBytes(16);    
  23.                 using (MemoryStream ms = new MemoryStream())    
  24.                 {    
  25.                     using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))    
  26.                     {    
  27.                         cs.Write(clearBytes, 0, clearBytes.Length);    
  28.                         cs.Close();    
  29.                     }    
  30.                     encryptString = Convert.ToBase64String(ms.ToArray());    
  31.                 }    
  32.             }    
  33.             return encryptString;    
  34.         }    
  35.     
  36.         public static string Decrypt(string cipherText)    
  37.         {    
  38.             string EncryptionKey = "0ram@1234xxxxxxxxxxtttttuuuuuiiiiio";  //we can change the code converstion key as per our requirement, but the decryption key should be same as encryption key    
  39.             cipherText = cipherText.Replace(" ""+");    
  40.             byte[] cipherBytes = Convert.FromBase64String(cipherText);    
  41.             using (Aes encryptor = Aes.Create())    
  42.             {    
  43.                 Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {      
  44.             0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76      
  45.         });    
  46.                 encryptor.Key = pdb.GetBytes(32);    
  47.                 encryptor.IV = pdb.GetBytes(16);    
  48.                 using (MemoryStream ms = new MemoryStream())    
  49.                 {    
  50.                     using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))    
  51.                     {    
  52.                         cs.Write(cipherBytes, 0, cipherBytes.Length);    
  53.                         cs.Close();    
  54.                     }    
  55.                     cipherText = Encoding.Unicode.GetString(ms.ToArray());    
  56.                 }    
  57.             }    
  58.             return cipherText;    
  59.         }      
  60.     }    
  61. }    
Step 4
 
Let's write a code for registering a new user on Register button click event. Please find the below code for your reference.
  1. using System.Collections.Generic;    
  2. using System.ComponentModel;    
  3. using System.Data;    
  4. using System.Drawing;    
  5. using System.Linq;    
  6. using System.Text;    
  7. using System.Windows.Forms;    
  8. using System.Data.SqlClient;    
  9.     
  10. namespace EncryptionandDecryption    
  11. {    
  12.     public partial class Form1 : Form    
  13.     {    
  14.         public Form1()    
  15.         {    
  16.             InitializeComponent();    
  17.         }    
  18.         SqlConnection con = new SqlConnection("Data Source=172.18.1.3;Initial Catalog=LoginDB;User ID=prog;Password=XqvF^D2$wJ");    
  19.     
  20.         private void btnRegister_Click(object sender, EventArgs e)    
  21.         {    
  22.             if (txtUserName.Text != "" && txtPassword.Text != "" && txtConfirmPassword.Text != "")  //validating the fields whether the fields or empty or not  
  23.             {    
  24.                 if (txtPassword.Text.ToString().Trim().ToLower() == txtConfirmPassword.Text.ToString().Trim().ToLower()) //validating Password textbox and confirm password textbox is match or unmatch    
  25.                 {    
  26.                     string UserName = txtUserName.Text;    
  27.                     string Password = Cryptography.Encrypt(txtPassword.Text.ToString());   // Passing the Password to Encrypt method and the method will return encrypted string and stored in Password variable.  
  28.                     con.Open();    
  29.                     SqlCommand insert=new SqlCommand("insert into tblUserRegistration(UserName,Password)values('"+UserName+"','"+Password+"')",con);    
  30.                     insert.ExecuteNonQuery();    
  31.                     con.Close();    
  32.                     MessageBox.Show("Record inserted successfully""Success", MessageBoxButtons.OK, MessageBoxIcon.Information);    
  33.                 }    
  34.                 else    
  35.                 {    
  36.                     MessageBox.Show("Password and Confirm Password doesn't match!.. Please Check..""Error", MessageBoxButtons.OK, MessageBoxIcon.Information);  //showing the error message if password and confirm password doesn't match  
  37.                 }    
  38.             }    
  39.             else    
  40.             {    
  41.                 MessageBox.Show("Please fill all the fields!..""Error", MessageBoxButtons.OK, MessageBoxIcon.Information);  //showing the error message if any fields is empty  
  42.             }    
  43.         }    
  44.     }    
  45. }    
Let's create a new registration and check the DB how the password has stored. Please find the below images for your reference.

 
 
 
Step 5
 
Now, we will design our login form and compare with DB. But here, we have encrypted our password in DB.The user is not aware of that. So in the back-end, we have to decrypt the user password and need to check.
 
Let's see how to do that.
 
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.ComponentModel;    
  4. using System.Data;    
  5. using System.Drawing;    
  6. using System.Linq;    
  7. using System.Text;    
  8. using System.Windows.Forms;    
  9. using System.Data.SqlClient;    
  10.     
  11. namespace EncryptionandDecryption    
  12. {    
  13.     public partial class Login : Form    
  14.     {    
  15.         public Login()    
  16.         {    
  17.             InitializeComponent();    
  18.         }    
  19.        SqlConnection con = new SqlConnection("Data Source=RAMESH-PC;Initial Catalog=LoginDB;Integrated Security=True");    
  20.         private void btnLogin_Click(object sender, EventArgs e)    
  21.         {    
  22.             string Password = "" ;    
  23.             bool IsExist = false;    
  24.             con.Open();    
  25.             SqlCommand cmd = new SqlCommand("select * from tblUserRegistration where UserName='" + txtUserName.Text + "'", con);    
  26.             SqlDataReader sdr = cmd.ExecuteReader();    
  27.             if (sdr.Read())    
  28.             {    
  29.                 Password = sdr.GetString(2);  //get the user password from db if the user name is exist in that.  
  30.                 IsExist = true;    
  31.             }    
  32.             con.Close();    
  33.             if (IsExist)  //if record exis in db , it will return true, otherwise it will return false  
  34.             {    
  35.                 if (Cryptography.Decrypt(Password).Equals(txtPassword.Text))    
  36.                 {    
  37.                     MessageBox.Show("Login Success""Success", MessageBoxButtons.OK, MessageBoxIcon.Information);    
  38.                     Form1 frm1 = new Form1();    
  39.                     frm1.ShowDialog();    
  40.                 }    
  41.                 else    
  42.                 {    
  43.                     MessageBox.Show("Password is wrong!...""error", MessageBoxButtons.OK, MessageBoxIcon.Information);    
  44.                 }    
  45.                   
  46.             }    
  47.             else  //showing the error message if user credential is wrong  
  48.             {    
  49.                 MessageBox.Show("Please enter the valid credentials""error", MessageBoxButtons.OK, MessageBoxIcon.Information);    
  50.             }    
  51.                
  52.         }    
  53.     }    
  54. }    
Thanks for reading my article. Please post comments if you have any feedback or queries.


Similar Articles