In a previous article, I delved into the intricacies of sending user confirmation emails after registration in ASP.NET using C# (link). Now, let's explore an essential aspect of web development—how to encode and decode passwords in ASP.NET registration and login pages using C# programming.
These coding practices are crucial for enhancing security by ensuring that user passwords are stored and transmitted in a secure manner.
Understanding Encoding and Decoding
Encode :
Encoding involves converting a password into a random or meaningless string of characters. This is a critical step in securing sensitive information. For example, a password like "Tiger@123" might be encoded as "cHJhZGVlcEAxMjM=" before storage.
Decode :
Decoding is the reverse process of encoding. It is used to convert the encoded password back to its original form. For instance, decoding "cHJhZGVlcEAxMjM=" would yield the original password "Tiger@123."
Database Setup
Before diving into the code, create a database table to store user registration information. Use the following SQL script to set up the 'Registration' table:
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 for Registration Page
The registration page's HTML markup includes form elements for capturing the username, password, and email ID. Mandatory field validation is applied using ASP.NET validators.
<%@ 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 for Password Encryption
In the code-behind file (Registration.aspx.cs), password encryption is handled using the Encrypt_Password method, which converts the password into a Base64-encoded string before storing it in the database.
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;
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);
}
// Method to encrypt the password
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;
}
}
HTML Markup for Login Page
The login page's HTML markup captures the username and password for authentication, with a link to the registration page for new users.
<%@ 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 Password Decryption
In the login page's code-behind file (login.aspx.cs), the Decrypt_Password method is used to decode the stored password from the database before authentication.
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;
}
}
Conclusion
Implementing secure password management practices is paramount in web development. The combination of encoding and decoding passwords adds an extra layer of protection, ensuring that sensitive user information remains confidential. By following these guidelines and incorporating the provided code snippets into your ASP.NET project, you can enhance the security of user credentials and contribute to a more robust authentication system.
0 Comments