Search content within the blog

Wednesday, May 13, 2009

Hashed passwords with salt and generating random passwords in asp.net

Hashed poasswords are one-way encryption and hence cannot be decrypted.
The salt is used to prevent the password hacking and make passwords in databse more secured.


logic is as follows....

your password + salt (unique for every user) = total password which will be stored in databse as follows...

username      password-hashed      salt
1      3423784safjkshf      hjh##
2      dfjsdkfjdf32432      jkh&&

so while validating passwords logic is as follows.....

if(supplied-password+ salt(in database)==hashedpassword)
valid data
else
invalid data


The encryption algorithm used is SHA1 Algorithm....
Also logic to generate random passwords exists....

The code is self explanatory.....

ASPX Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="HashedPasswords.aspx.cs" Inherits="Encryption_Decryption_HashedPasswords" %>

<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<br />
Enter usename:
<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox><br />
Enter password:
<asp:TextBox ID="txtpassword" runat="server"></asp:TextBox>
<br />
                       
    
<asp:Button ID="Button1" runat="server" Text="Store password" OnClick="Button1_Click" /> 
<br />
<br />
Enter usename:
<asp:TextBox ID="txtverifyusername" runat="server"></asp:TextBox><br />
Enter password:
<asp:TextBox ID="txtverifypassword" runat="server"></asp:TextBox>
<br />
                       
    
<asp:Button ID="Button2" runat="server" Text="Verify password" OnClick="Button2_Click" /> 
</div>

<div>
Click the button to generate random passwords to store in database :
<asp:Button ID="Button3" runat="server" Text="Generate passsword" OnClick="Button3_Click" />
</div>
</form>
</body>
</html>

ASPX.CS Code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Encryption_Decryption_HashedPasswords : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
string salt=Password.CreateSalt(5);
string hashedPassword = Password.CreatePasswordHash(txtpassword.Text.Trim(), salt);
Response.Write("Salt generated:"+salt+"<br>");
Response.Write("Hashed password:" + hashedPassword + "<br>");
ViewState["salt"] = salt;
ViewState["Hashedpassword"] = hashedPassword;

}
protected void Button2_Click(object sender, EventArgs e)
{

string suppliedpasswordhash = Password.CreatePasswordHash(txtverifypassword.Text.Trim(), ViewState["salt"].ToString());
if(suppliedpasswordhash.Equals(ViewState["Hashedpassword"].ToString()))
{
Response.Write("valid crendentials....");
}
else{
Response.Write("Invalid crendentials....");
txtpassword.Text=txtUsername.Text=string.Empty;
}
}
protected void Button3_Click(object sender, EventArgs e)
{
string randomPassword = Password.CreateRandomPassword(8);
string salt = Password.CreateSalt(5);
string hashedPassword = Password.CreatePasswordHash(randomPassword, salt);
Response.Write("Random password:" + randomPassword + "<br>");
Response.Write("Salt generated:" + salt + "<br>");
Response.Write("Hashed password:" + hashedPassword + "<br>");
}
}


Add a file called password.cs in appcode section...for the above code to work... the code for the file is as follows...

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;

///
/// Summary description for Password
///

public class Password
{
public Password()
{
//
// TODO: Add constructor logic here
//
}
public static string CreateSalt(int size)
{
//Generate a cryptographic random number.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
rng.GetBytes(buff);

// Return a Base64 string representation of the random number.
return Convert.ToBase64String(buff);
}
public static string CreatePasswordHash(string pwd, string salt)
{
string saltAndPwd = String.Concat(pwd, salt);
string hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "sha1");

return hashedPwd;
}
public static string CreateRandomPassword(int PasswordLength)
{
String _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789!@#$%^&*()";
Byte[] randomBytes = new Byte[PasswordLength];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
char[] chars = new char[PasswordLength];
int allowedCharCount = _allowedChars.Length;

for (int i = 0; i < PasswordLength; i++)
{
chars[i] = _allowedChars[(int)randomBytes[i] % allowedCharCount];
}

return new string(chars);
}
}

No comments:

Post a Comment