How to Encode and Decode Password in Asp.net Registration and Login Page using C#


In previous article I explained How to Send User Confirmation Email after Registration in ASP.NET by using C# Coding. Now i'm going to explain How to Encode and Decode Password in Asp.net Registration and Login Page using C# Programming.

How to Encode and Decode Password in Asp.net Registration and Login Page using C#

These Articles will help you in coding how to use encoding and decoding class in programming.
Encode :
Encoding is used to convert password to random char (or) Meaningless char
For Example : Password : Tiger@123 | Encode : cHJhZGVlcEAxMjM=
Encode is used to convert password and stored into Database(Find Register Page Code Below)
Decode :
Decoding is exactly viceverse of Encoding.
For Example : Decode : cHJhZGVlcEAxMjM= | Password : Tiger@123
Decode is used to convert Encoded password from Database.(Find Login Page Code Below)

Create Database

USE [master]
GO
/****** Object:  Table [dbo].[Registration]    Script Date: 04/07/2015 11:31:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Registration](
 [username] [nvarchar](50) NULL,
 [password] [nvarchar](50) NULL,
 [emailid] [nvarchar](50) NULL,
 [activation_code] [uniqueidentifier] NULL,
 [account_status] [nvarchar](15) NULL
) ON [PRIMARY]
GO

HTML Markup : Create Registration Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Registration.aspx.cs" Inherits="Registration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <table class="table">
     <tr>
      <th class="table_th" colspan="2">Registration</th>
     </tr>
     <tr>
      <td colspan="2"></td>
     </tr>
      <tr>
       <td style="width:200px; text-align:center;">Username :</td>
       <td><asp:TextBox ID="txtusername" runat="server" CssClass="txtbox"></asp:TextBox>
           <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
               ControlToValidate="txtusername" >enter username</asp:RequiredFieldValidator>
          </td>
      </tr>
      <tr>
       <td style="width:200px; text-align:center;">Password :</td>
       <td><asp:TextBox ID="txtpassword" runat="server" CssClass="txtbox" TextMode="Password"></asp:TextBox>
           <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
               ControlToValidate="txtpassword">enter password</asp:RequiredFieldValidator>
          </td>
      </tr>
      <tr>
      <td style="width:200px; text-align:center;">Email ID :</td>
      <td><asp:TextBox ID="txtemailid" runat="server" CssClass="txtbox"></asp:TextBox><asp:RegularExpressionValidator
              ID="RegularExpressionValidator1" runat="server" 
              ControlToValidate="txtemailid" 
              ValidationExpression="\w+undefined[-+.']\w+)*@\w+undefined[-.]\w+)*\.\w+undefined[-.]\w+)*">please enter valid email addressundefinedabc@xyz.com)</asp:RegularExpressionValidator></td>
      </tr>
      <tr>
      <td colspan="2" align="center">
       <asp:Button ID="Btn_Register" runat="server" Text="Register" 
              onclick="Btn_Register_Click"/>
      </td>
      </tr>
     </table>
    </div>
    </form>
</body>
</html>

C# Coding

C# Coding : Namespace

Namespace for Encode & Decode :
using System.Text;
using System.Security.Cryptography;

Encode is used to convert password and stored into Database

  • private string Encrypt_Password(string password)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Security.Cryptography;

C# Coding : Button Click Event

public partial class Registration : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RCCon"].ConnectionString);
    SqlCommand cmd;   
     
    protected void Btn_Register_Click(object sender, EventArgs e)
    {
        string encry_password = Encrypt_Password(txtpassword.Text);
        cmd = new SqlCommand("insert into Registration values('" + txtusername.Text.ToLower() + "','" + encry_password + "','" + txtemailid.Text + "','" + activationCode + "','active')");
        cmd.Connection = con;
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        Session["user"] = txtusername.Text;
        Response.Redirect("Default.aspx?username="+txtusername.Text);
    }

C# Coding : Encript Password Method

    private string Encrypt_Password(string password)
    {
        string pwdstring = string.Empty;
        byte[] pwd_encode = new byte[password.Length];
        pwd_encode = Encoding.UTF8.GetBytes(password);
        pwdstring = Convert.ToBase64String(pwd_encode);
        return pwdstring;
    }  

}

HTMK Markup : Create Login Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <table class="table">
     <tr>
      <th colspan="2" class="table_th">Login Page</th>
     </tr>
      <tr >
       <td>Username :</td>
       <td><asp:TextBox ID="txtusername" runat='server' CssClass="txtbox"></asp:TextBox></td>
      </tr>
      <tr>
       <td >Password :</td>
       <td><asp:TextBox id="txtpassword" runat="server" CssClass="txtbox" TextMode="Password"></asp:TextBox></td>
      </tr>
      <tr>
       <td colspan="2" align="center">
           <asp:Button ID="Btn_Login" runat="server" onclick="Btn_Login_Click" Text="Login" />
       </td>
      </tr>
      <tr>
       <td colspan="2">
         Create a New Account : <a href="Registration.aspx">SignUp</a>
       </td>
      </tr>
      <tr>
       <td colspan="2" align="left">
        <label id="lblerror" runat="server"></label>
       </td>
      </tr>
     </table>
    </div>
    </form>
</body>
</html>

C# Coding for Login Page

Decode is used to convert Encoded password from Database
  • private string Decrypt_Password(string encryptpassword)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Text;
using System.IO;

public partial class login : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RCCon"].ConnectionString);

    protected void Btn_Login_Click(object sender, EventArgs e)
    {
        SqlDataAdapter da = new SqlDataAdapter("select * from Registration", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                string userid = ds.Tables[0].Rows[i]["username"].ToString();
                string pwd = Decrypt_Password(ds.Tables[0].Rows[i]["password"].ToString());
                string status = "active";
                if (status == ds.Tables[0].Rows[i]["account_status"].ToString())
                {
                    
                    if (userid == txtusername.Text.ToLower() && pwd == txtpassword.Text)
                    {
                        Response.Redirect("Default.aspx?Username=" + txtusername.Text);
                    }
                }
                
                    lblerror.InnerText = "Invalid Username and Password";

            }
        }
    }    
    private string Decrypt_Password(string encryptpassword)
    {
        string pwdstring = string.Empty;
        UTF8Encoding encode_pwd = new UTF8Encoding();
        Decoder Decode = encode_pwd.GetDecoder();
        byte[] todecode_byte = Convert.FromBase64String(encryptpassword);
        int charCount = Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
        char[] decoded_char = new char[charCount];
        Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
        pwdstring = new String(decoded_char);
        return pwdstring;
    }
}
0 Komentar untuk "How to Encode and Decode Password in Asp.net Registration and Login Page using C#"

Back To Top