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. namespace EncryptionandDecryption
  8. {
  9. public class Cryptography
  10. {
  11. public static string Encrypt(string encryptString)
  12. {
  13. string EncryptionKey = "0ram@1234xxxxxxxxxxtttttuuuuuiiiiio"; //we can change the code converstion key as per our requirement
  14. byte[] clearBytes = Encoding.Unicode.GetBytes(encryptString);
  15. using (Aes encryptor = Aes.Create())
  16. {
  17. Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {
  18. 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76
  19. });
  20. encryptor.Key = pdb.GetBytes(32);
  21. encryptor.IV = pdb.GetBytes(16);
  22. using (MemoryStream ms = new MemoryStream())
  23. {
  24. using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
  25. {
  26. cs.Write(clearBytes, 0, clearBytes.Length);
  27. cs.Close();
  28. }
  29. encryptString = Convert.ToBase64String(ms.ToArray());
  30. }
  31. }
  32. return encryptString;
  33. }
  34. public static string Decrypt(string cipherText)
  35. {
  36. 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
  37. cipherText = cipherText.Replace(" ", "+");
  38. byte[] cipherBytes = Convert.FromBase64String(cipherText);
  39. using (Aes encryptor = Aes.Create())
  40. {
  41. Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {
  42. 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76
  43. });
  44. encryptor.Key = pdb.GetBytes(32);
  45. encryptor.IV = pdb.GetBytes(16);
  46. using (MemoryStream ms = new MemoryStream())
  47. {
  48. using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
  49. {
  50. cs.Write(cipherBytes, 0, cipherBytes.Length);
  51. cs.Close();
  52. }
  53. cipherText = Encoding.Unicode.GetString(ms.ToArray());
  54. }
  55. }
  56. return cipherText;
  57. }
  58. }
  59. }
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. namespace EncryptionandDecryption
  10. {
  11. public partial class Form1 : Form
  12. {
  13. public Form1()
  14. {
  15. InitializeComponent();
  16. }
  17. SqlConnection con = new SqlConnection("Data Source=172.18.1.3;Initial Catalog=LoginDB;User ID=prog;Password=XqvF^D2$wJ");
  18. private void btnRegister_Click(object sender, EventArgs e)
  19. {
  20. if (txtUserName.Text != "" && txtPassword.Text != "" && txtConfirmPassword.Text != "") //validating the fields whether the fields or empty or not
  21. {
  22. if (txtPassword.Text.ToString().Trim().ToLower() == txtConfirmPassword.Text.ToString().Trim().ToLower()) //validating Password textbox and confirm password textbox is match or unmatch
  23. {
  24. string UserName = txtUserName.Text;
  25. 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.
  26. con.Open();
  27. SqlCommand insert=new SqlCommand("insert into tblUserRegistration(UserName,Password)values('"+UserName+"','"+Password+"')",con);
  28. insert.ExecuteNonQuery();
  29. con.Close();
  30. MessageBox.Show("Record inserted successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
  31. }
  32. else
  33. {
  34. 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
  35. }
  36. }
  37. else
  38. {
  39. MessageBox.Show("Please fill all the fields!..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information); //showing the error message if any fields is empty
  40. }
  41. }
  42. }
  43. }
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. namespace EncryptionandDecryption
  11. {
  12. public partial class Login : Form
  13. {
  14. public Login()
  15. {
  16. InitializeComponent();
  17. }
  18. SqlConnection con = new SqlConnection("Data Source=RAMESH-PC;Initial Catalog=LoginDB;Integrated Security=True");
  19. private void btnLogin_Click(object sender, EventArgs e)
  20. {
  21. string Password = "" ;
  22. bool IsExist = false;
  23. con.Open();
  24. SqlCommand cmd = new SqlCommand("select * from tblUserRegistration where UserName='" + txtUserName.Text + "'", con);
  25. SqlDataReader sdr = cmd.ExecuteReader();
  26. if (sdr.Read())
  27. {
  28. Password = sdr.GetString(2); //get the user password from db if the user name is exist in that.
  29. IsExist = true;
  30. }
  31. con.Close();
  32. if (IsExist) //if record exis in db , it will return true, otherwise it will return false
  33. {
  34. if (Cryptography.Decrypt(Password).Equals(txtPassword.Text))
  35. {
  36. MessageBox.Show("Login Success", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
  37. Form1 frm1 = new Form1();
  38. frm1.ShowDialog();
  39. }
  40. else
  41. {
  42. MessageBox.Show("Password is wrong!...", "error", MessageBoxButtons.OK, MessageBoxIcon.Information);
  43. }
  44. }
  45. else //showing the error message if user credential is wrong
  46. {
  47. MessageBox.Show("Please enter the valid credentials", "error", MessageBoxButtons.OK, MessageBoxIcon.Information);
  48. }
  49. }
  50. }
  51. }
Thanks for reading my article. Please post comments if you have any feedback or queries.