Announcement

Store Password in Encrypted form

Store Password in Encrypted Form

Now a days security is a big issue for any organisation or an individual. Whether you do surfing on internet or use your ATM. Everywhere we can find in some or the other way to secure our data or transaction or just to be on the safe side.

Software Engineers or Developers try hard to provide security for the applications they built. One common way to provide security is to provide Login credentials for their applications. To improve it further, 3-attempts login feature is provided. After 3 unsuccessful attempt, the applications gets blocked.

There are lot of other ways to provide security.

Now, what is more important is to secure your data. i.e., What if somebody peeps into your database? The person will get to know users credentials of your system or application.

One way to prevent this is to store password in encrypted form.

So let us learn how to store password in encrypted form using a reliable MD5 algorithm.


First you need to have your UI ready. In this example, UI will contain a text box for entering username and a password field for entering password. A login button is provided for login purpose and a cancel button.

The code for Login View is as



@{
ViewBag.Title = "Login Page";
}

<p id= "msg" style="color: Red"><b>
@if (ViewBag.errorMessage != null)
{
@ViewBag.errorMessage;
ViewBag.errorMessage = null;
}
</b></p>

<div id="messageTable">
@if (Session["errorMessage"] != null)
{
<table>
<tr>
<td class="errorMessage">
<span class="errorIcon"> </span>@Session["errorMessage"]
<span class="closeIcon" onclick="javascript:HideMessage();"> </span>
</td>
</tr>
</table>

Session["errorMessage"] = null;
}
@if (Session["successMessage"] != null)
{
<table id="mmessageTable">
<tr>
<td class="successMessage">
<span class="successIcon"> </span>
@Session["successMessage"]
<span class="closeIcon" onclick="javascript:HideMessage();"> </span>
</td>
</tr>
</table>

Session["successMessage"] = null;
}
</div>
@using (Html.BeginForm("Index","Home",FormMethod.Post))
{
<div class="LoginDiv" align="center">
<div class="Formarquee" style="width:600px; height:30px; background-color: #4A6B82; color: #FFFFFF; font-family: Comic Sans MS; font-size:12pt; font-weight: bold;" >
<marquee behavior="alternate" direction="left">
TECHINERS Web Application</marquee>
</div>

<div class="Heading" align="Center" style="background-color:#EEEEEE;" >
AMS</div>
<div class="UserDetails">
<span class="info">Enter Login ID and Password to sign in</span><br />
<br />
<br />
<span class="LogoDiv"></span>
<div>
<b>Login ID: </b>&nbsp
@Html.TextBox("txtUserName", null, new { @class = "TextBox", @id = "txtloginId" })
</div>
<br />
<div>
<b>Password: </b>  @Html.Password("txtPassword", null, new { @class = "TextBox", @id = "txtpassword" })
</div>
</div>

<div class="LoginResetButtons">
<div style="padding-top:7px;" > 
<button id="Loginbtn" type="submit" style="width:70px; height:32px; border:none; font-weight: bold;background-color:transparent;
" >OK</button>
<button id="Resetbtn" type="reset" style="width:100px; height:32px; background-color:transparent;
border:none; font-weight: bold;" > Cancel</button>
</div>
</div>
</div>
<br />
<br />
<br />
<div style="text-decoration: overline; font-family: Arial, Helvetica, sans-serif; font-size: small; margin-top:320px; margin-left:350px; display:block; position: fixed;" >Copyright © 2014 techiners.in</div> 
}

Now, on the click of OK button which is of type submit, we will have to write controller's Action method with its method attribute as [HttpPost]. Get the values of the username and password using FormCollection class. This can be done as:



public ActionResult Index(FormCollection formCollection)
{
string userLogin = formCollection["txtUserName"].ToString();
string userPassword = formCollection["txtPassword"].ToString();
}


where "txtUserName" is the name which is provided in the view to HTML Helper i.e.,

@Html.TextBox("txtUserName",null,new { @class = "TextBox", @id = "txtloginId" })

here null is the object value. Don't need to pass anything, so kept it as null, then we created two objects as ID and CLASS. These are but the HTML Attributes.

Similarly, we have done for Password.

Now, assign the user name to the Session object to retrieve the username on all pages and to keep the session alive.

Now comes the main part i.e., encrypting the password. The password is encrypted using the MD5CryptoServiceProvider class.

For this to use, don't forget to use the following namespace: System.Security.Cryptography;

Create an object of MD5 class using MD5CryptoServiceProvider class as

MD5 md5 = new MD5CryptoServiceProvider();

and compute the hash using ACSIIEncoding GetBytes() method as:

md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(password));

Assign this hash to an array of byte called as result:

byte[] result = md5.Hash;

Now using StringBuilder class append to each byte "x2" in the following way:




StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < result.Length; i++) { strBuilder.Append(result[i].ToString("x2")); }


You will get the encrypted password in StringBuilder object i.e., strBuilder.

The complete code for this is in Controller as :



[HttpPost]
public ActionResult Index(FormCollection formCollection)
{
   string userLogin = formCollection["txtUserName"].ToString();
   string userPassword = formCollection["txtPassword"].ToString();
   string loginId = userLogin;
   string password = userPassword;
   Session["loginId"] = loginId;

//Encrypt Password using md5.Hash code
   string encryptedPassword = null;
   if (password != null)
   {
      MD5 md5 = new MD5CryptoServiceProvider();
      md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(password));
      byte[] result = md5.Hash;
      StringBuilder strBuilder = new StringBuilder();
      for (int i = 0; i < result.Length; i++) 

      {
         /*get Encrypted password in string named password. */
        strBuilder.Append(result[i].ToString("x2"));
      } 
      encryptedPassword = strBuilder.ToString(); 
   }


   Business.Login bizLogin = new Business.Login(); 



   int count = bizLogin.UserLogin(loginId, encryptedPassword); 



   int userType = context.SystemUsers.Where(x => x.UserName.Equals(userLogin) 

&& x.Password.Equals(encryptedPassword)).Select(y=>y.UserType).FirstOrDefault();



  Session["userType"] = userType;




   /*if loginId and password is correct it returns 1 else 0.*/



  if (count == 1)

  {
      return RedirectToAction("Home","Home");
  }
  else
  {
      Session["errorMessage"] = "Invalid Login Id or Password";
      return RedirectToAction("Index");
  }

}

No comments: