NOTE: [This encryption technique is a one way technique means you can encrypt the string but you cannot decrypt it back to it's original form, So for password recovery you can either send the reset link to the user's email address or you can ask the Security Question. For authentication password will be compared on the basis of Hash Values]
Following are the tools I've used:-
- Visual Studio 2008 Professional Edition
- Microsoft SQL Server 2005 Management Edition
First I created my database "HashDB" and then table as "utable" with columns 1. uname (primary key) 2. upwd.

and this is the table

Now, moving on to Solution Explorer, I've taken 3 .aspx pages:-
- Default Page (This page is used to register user)
- Login Page (This page is used to login)
- Home Page (This page is used as Home Page on successful login). On PageLoad event of this page I've retrieved the Session that is why it is kept blank and I haven't used any image


Now, I've created a Class File named as "HashString" in App_Code directory of my website. This class will be used to hash the input string and return the encrypted version of the string
There will be two namespaces through which we'll implement our security module;-
- System.Text
- System.Security.Cryptography
I've created a static function "CalculateHash" that will take string as argument and return the same.
using System.Text;
using System.Security.Cryptography;
public class HashString
{
#region Calculate Hash
public static string CalculateHash(string str)
{
byte[] originalBytes, encryptedBytes;
MD5 md5 = new MD5CryptoServiceProvider();
originalBytes = ASCIIEncoding.Default.GetBytes(str);
encryptedBytes = md5.ComputeHash(originalBytes);
str = BitConverter.ToString(encryptedBytes);
return str;
}
#endregion
}
The "str" string variable will be our password and now, we've declared two byte array as "originalBytes", "encryptedBytes". MD5 class variable is initialized by the constructor of MD5CryptoServiceProvider. ASCIIEncoding class is used to get the bytes from the string "str" and store them into "originalBytes" array. Now, the main view, ComputeHash is an instance method is called through the md5 object and given the arguments as byte array i.e. "originalBytes" and is stored into the byte array "encryptedArray". Finally, with the use of BitConverter class it's static method ToString() is called to convert the byte array "encryptedBytes" into hexadecimal string.
Now, back to Default page where users will get registered . This the code of "SUBMIT" button:
using System.Security.Cryptography;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["server"].ConnectionString);
protected void submit_Click(object sender, EventArgs e)
{
string uname = TextBox1.Text;
string upwd = HashString.CalculateHash(TextBox2.Text);
try
{
string sql = "insert into utable(uname, upwd) values(@unameParam,@upwdParam)";
var cmd = new SqlCommand(sql, cn);
cmd.Parameters.AddWithValue("unameParam", uname);
cmd.Parameters.AddWithValue("upwdParam", upwd);
cn.Open();
cmd.ExecuteNonQuery();
Response.Write("Record Inserted");
}
catch (Exception ex)
{
Response.Write("ERROR " + ex.ToString());
}
finally
{
cn.Close();
}
}
}
same thing, we've to use two namespaces as System.Text, System.Security.Cryptography. Now, I've stored my connection string in web.config file as
<connectionStrings>
<add name="server" providerName="System.Data.SqlClient" connectionString="Data Source=.;Initial Catalog=HashDB;Integrated Security=True;Pooling=False"/>
</connectionStrings>
I've stored the values of our both text boxes in two string variables as "uname" and "upwd" which are user id and password respectively. But, notice we haven't stored the password directly rather the control is transferred to Class HashString in App_Code by calling it's static method CalculateHash with arguments as string which is password from the textbox. After performing all the hashing functionalities the CalculateHash method returns the string value and stores it in "upwd" variable. To store the row into the database table a normal insertion is performed.
Login Page, "LOGIN" button code:
using System.Data.SqlClient;
using System.Security.Cryptography;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["server"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
string uname = TextBox1.Text;
string upwd = HashString.ComputeHash(TextBox2.Text);
try
{
string sql = "select uname, upwd from utable where uname = @unameParam and upwd = @upwdParam";
var cmd = new SqlCommand(sql, cn);
cmd.Parameters.AddWithValue("@unameParam", uname);
cmd.Parameters.AddWithValue("@upwdParam", upwd);
cn.Open();
var dread = cmd.ExecuteReader();
if (dread.HasRows)
{
dread.Read();
//Create Cookies / Sessions
Session.Add("id", dread["uname"].ToString());
Response.Redirect("Home.aspx");
}
else
{
Response.Write("Invalid Username/Password");
}
}
catch (Exception ex)
{
Response.Write("ERROR: " + ex.ToString());
}
finally
{
cn.Close();
}
}
}
For authentication purpose we'll compute the hash of the password given by the user and a matching password will be find out in the database table by the use of SELECT Query. if authenticated then SqlDataReader wll be used to retrieve the id, store it in Session for state management and redirect to Home Page. Finally, on the page load event of this page I've retrieved the Session for authorization.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["id"] != null)
Response.Write("Hello, " + Session["id"].ToString());
else
Response.Redirect("Login.aspx");
}
I hope my tutorial helped you, Good Luck





MultiQuote




|