How To Login With Encrypted Password In ASP.NET

In this blog, I will demonstrate how to create a login form with an encrypted password using ASP.NET step by step. I will decrypt the password from the database and login to the dashboard. I will implement sign out functionality and also prevent browser forward and backward using JavaScript.

Introduction

In this blog, I will demonstrate how to create a login form with an encrypted password using ASP.NET step by step. I will decrypt the password from the database and login to the dashboard. Also, I will implement the sign out functionality using JavaScript.

 

Step 1

Open SQL Server 2014 and create database table UserRegistration.
  1. CREATE TABLE [dbo].[UserRegistration](  
  2.     [ID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [nvarchar](50) NULL,  
  4.     [Email] [nvarchar](50) NULL,  
  5.     [PhoneNumber] [nvarchar](50) NULL,  
  6.     [Password] [nvarchar](50) NULL,  
  7.     [Created] [datetime] NULL,  
  8.  CONSTRAINT [PK_UserRegistration] PRIMARY KEY CLUSTERED   
  9. (  
  10.     [ID] ASC  
  11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
  12. ) ON [PRIMARY]  
  13.   
  14. GO  
  1. CREATE procedure [dbo].[spRegister]  
  2. (  
  3. @Name nvarchar(50),  
  4. @Email nvarchar(50),  
  5. @PhoneNumber nvarchar(50),  
  6. @Password nvarchar(50),  
  7. @Created datetime  
  8. )  
  9. as  
  10. begin  
  11. insert into [dbo].[UserRegistration](Name,Email,PhoneNumber,Password,Created)  
  12. values(@Name,@Email,@PhoneNumber,@Password,GETDATE())  
  13. end  
  1. Create procedure [dbo].[spLogin]  
  2. (  
  3. @Email nvarchar(50),  
  4. @Password nvarchar(50)  
  5. )  
  6. as  
  7. begin  
  8. Select COUNT(*) from UserRegistration where Email=@Email and Password=@Password   
  9. end  
How To Login With Encrypted Password In ASP.NET

Step 2

Open Visual Studio 2015, create an empty web application project and give it a meaningful name. Right-click or double-click on web config file and database connection in it.
  1. <connectionStrings>  
  2.   <add name="DBCS" connectionString="data source=DESKTOP-M021QJH\SQLEXPRESS; database=SampleDB; integrated security=true;"/>  
  3. </connectionStrings>  

Add the below line of code if you get a validation error.

  1. <appSettings>  
  2.     <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />  
  3. </appSettings>  

Step 3

Right-click on the project, select Add, choose web form, and name it LoginForm.

Add the script and bootstrap 4 style plugin files in the header section of the login page.

  1. link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">  
  2.     <link href="Content/bootstrap.min.css" rel="stylesheet" />  
  3.     <script src="scripts/jquery-3.3.1.min.js"></script>  
  4.     <script src="scripts/bootstrap.min.js"></script>  
  5.     <style>  
  6.         .bottom {  
  7.             margin-bottom: 5px !important;  
  8.         }  
  9.     </style>  
  10.        <script type="text/javascript">  
  11.         function preventBack() { window.history.forward(); }  
  12.         setTimeout("preventBack()", 0);  
  13.         window.onunload = function () { null };  
  14.     </script>  

Design the web form using textbox control, button control, and validation control. Apply the respective bootstrap 4 class.

  1. <body>  
  2.     <form id="form1" runat="server">  
  3.         <div class="container py-4">  
  4.             <div class="col-md-5 offset-md-3">  
  5.                 <div class="card card-outline-secondary rounded-0">  
  6.                     <div class="card-header bg-success rounded-0">  
  7.                         <h4 class="text-center text-uppercase text-white">Login</h4>  
  8.                     </div>  
  9.                     <div class="card-body">  
  10.                         <div class="form-group bottom">  
  11.                             <label>Username (Email)</label>  
  12.                             <div class="input-group">  
  13.                                 <div class="input-group-prepend">  
  14.                                     <div class="input-group-text"><i class="fa fa-envelope"></i></div>  
  15.                                 </div>  
  16.                                 <asp:TextBox ID="txtEmail" runat="server" CssClass="form-control"></asp:TextBox>  
  17.                             </div>  
  18.                             <asp:RequiredFieldValidator ID="rfvEmail" Display="Dynamic" ControlToValidate="txtEmail" CssClass="text-danger" runat="server" ErrorMessage="Please enter email address"></asp:RequiredFieldValidator>  
  19.                             <asp:RegularExpressionValidator ID="revEmail" ControlToValidate="txtEmail" CssClass="text-danger" runat="server" ErrorMessage="Enter valid email" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>  
  20.                         </div>  
  21.                         <div class="form-group bottom">  
  22.                             <label>Password</label>  
  23.                             <div class="input-group">  
  24.                                 <div class="input-group-prepend">  
  25.                                     <div class="input-group-text"><i class="fa fa-lock"></i></div>  
  26.                                 </div>  
  27.                                 <asp:TextBox ID="txtPassword" TextMode="Password" runat="server" CssClass="form-control"></asp:TextBox>  
  28.                             </div>  
  29.                             <asp:RequiredFieldValidator ID="rfvPassword" ControlToValidate="txtPassword" CssClass="text-danger" runat="server" ErrorMessage="Please enter password"></asp:RequiredFieldValidator>  
  30.                         </div>  
  31.                         <div class="form-group">  
  32.                             <asp:Button ID="btnLogin" CssClass="btn btn-success rounded-0 btn-block" runat="server" Text="Login" OnClick="btnLogin_Click" />  
  33.                         </div>  
  34.                         <div class="form-group text-center">  
  35.                             <asp:HyperLink ID="linkRegistration" NavigateUrl="~/RegisterForm.aspx" CssClass="text-primary btn-link" runat="server">New User</asp:HyperLink>  
  36.                             <asp:HyperLink ID="linkForgotPassword" NavigateUrl="~/ForgotPassword.aspx" CssClass="text-primary btn-link"  runat="server">Forgot Password</asp:HyperLink>  
  37.                         </div>  
  38.                         <div class="text-center">  
  39.                              <asp:Label ID="lblMessage" CssClass="text-center" runat="server"></asp:Label>  
  40.                         </div>                        
  41.                     </div>  
  42.                 </div>  
  43.             </div>  
  44.         </div>  
  45.     </form>  
  46. </body>  
Step 4
 
Double-click on the Login button and write the following C# code.

Add the following namespace.

  1. using System.Configuration;  
  2. using System.Data;  
  3. using System.Data.SqlClient;  
  4. using System.Security.Cryptography;  
  5. using System.IO;  
  6. using System.Text;  

Complete code of the login page -

  1. using System;  
  2. using System.Configuration;  
  3. using System.Data;  
  4. using System.Data.SqlClient;  
  5. using System.IO;  
  6. using System.Security.Cryptography;  
  7. using System.Text;  
  8.   
  9. namespace UserRegistration_Demo  
  10. {  
  11.     public partial class LoginForm : System.Web.UI.Page  
  12.     {  
  13.         protected void Page_Load(object sender, EventArgs e)  
  14.         {  
  15.             if (!IsPostBack)  
  16.             {  
  17.                 Session["Username"] = txtEmail.Text;  
  18.             }  
  19.         }  
  20.         private string Decrypt(string clearText)  
  21.         {  
  22.             string EncryptionKey = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";  
  23.             byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);  
  24.             using (Aes encryptor = Aes.Create())  
  25.             {  
  26.                 Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });  
  27.                 encryptor.Key = pdb.GetBytes(32);  
  28.                 encryptor.IV = pdb.GetBytes(16);  
  29.                 using (MemoryStream ms = new MemoryStream())  
  30.                 {  
  31.                     using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))  
  32.                     {  
  33.                         cs.Write(clearBytes, 0, clearBytes.Length);  
  34.                         cs.Close();  
  35.                     }  
  36.                     clearText = Convert.ToBase64String(ms.ToArray());  
  37.                 }  
  38.             }  
  39.             return clearText;  
  40.         }  
  41.         protected void btnLogin_Click(object sender, EventArgs e)  
  42.         {  
  43.               
  44.             string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  45.             using (SqlConnection con=new SqlConnection(CS))  
  46.             {  
  47.                 SqlCommand cmd = new SqlCommand("spLogin", con);  
  48.                 cmd.CommandType = CommandType.StoredProcedure;  
  49.                 con.Open();  
  50.                 cmd.Parameters.AddWithValue("@Email",txtEmail.Text.Trim());  
  51.                 cmd.Parameters.AddWithValue("@Password", Decrypt(txtPassword.Text.Trim()));  
  52.                 int Username = (Int32)cmd.ExecuteScalar();  
  53.                 if (Username == 1)  
  54.                 {  
  55.                     Session["Username"] = txtEmail.Text;  
  56.                     Response.Redirect("Welcome.aspx");  
  57.                     Session.RemoveAll();  
  58.                       
  59.                 }  
  60.                 else  
  61.                 {  
  62.                     lblMessage.ForeColor = System.Drawing.Color.Red;  
  63.                     lblMessage.Text = "Invalid username and password";  
  64.                 }  
  65.             }  
  66.         }  
  67.     }  
  68. }  

Step 5

Run the project by pressing ctrl+F5.

Screenshot 1

 

How To Login With Encrypted Password In ASP.NET
Screenshot 2

 

How To Login With Encrypted Password In ASP.NET
Screenshot 3

If we have entered a wrong username or password.

How To Login With Encrypted Password In ASP.NET

Step 6 

In the dashboard, add a link button.
  1. <asp:LinkButton ID="linkbtnSignOut" CssClass="nav-link text-white" runat="server" OnClick="linkbtnSignOut_Click">Sign out</asp:LinkButton>  

Step 7

Double click on the sign out link button.
  1. using System;  
  2.   
  3. namespace UserRegistration_Demo  
  4. {  
  5.     public partial class Welcome : System.Web.UI.Page  
  6.     {  
  7.         protected void Page_Load(object sender, EventArgs e)  
  8.         {  
  9.             if (!IsPostBack)  
  10.             {  
  11.                 lblUsername.Text = Session["Username"].ToString();  
  12.             }  
  13.         }  
  14.   
  15.         protected void linkbtnSignOut_Click(object sender, EventArgs e)  
  16.         {  
  17.             Session.RemoveAll();  
  18.             Response.Redirect("LoginForm.aspx");  
  19.         }  
  20.     }  
  21. }  

Screenshot 4

 

How To Login With Encrypted Password In ASP.NET