Click here to Skip to main content
15,896,201 members
Articles / Mobile Apps / Windows Mobile

Manually validating an ASP.NET user account with a SHA1 hashed password

Rate me:
Please Sign up or sign in to vote.
4.78/5 (5 votes)
16 Jan 2009CPOL 33.8K   3   16  
How to manually validate an ASP.NET Roles and Membership password using SHA1.
<!--------------------------------------------------------------------------->  
<!--                           INTRODUCTION                                

 The Code Project article submission template (HTML version)

Using this template will help us post your article sooner. To use, just 
follow the 3 easy steps below:
 
     1. Fill in the article description details
     2. Add links to your images and downloads
     3. Include the main article text

That's all there is to it! All formatting will be done by our submission
scripts and style sheets. 

-->  
<!--------------------------------------------------------------------------->  
<!--                        IGNORE THIS SECTION                            -->
<html>
<head>
<title>The Code Project</title>
<Style>
BODY, P, TD { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt }
H2,H3,H4,H5 { color: #ff9900; font-weight: bold; }
H2 { font-size: 13pt; }
H3 { font-size: 12pt; }
H4 { font-size: 10pt; color: black; }
PRE { BACKGROUND-COLOR: #FBEDBB; FONT-FAMILY: "Courier New", Courier, mono; WHITE-SPACE: pre; }
CODE { COLOR: #990000; FONT-FAMILY: "Courier New", Courier, mono; }
</style>
<link rel="stylesheet" type=text/css href="http://www.codeproject.com/styles/global.css">
</head>
<body bgcolor="#FFFFFF" color=#000000>
<!--------------------------------------------------------------------------->  


<!-------------------------------     STEP 1      --------------------------->
<!--  Fill in the details (CodeProject will reformat this section for you) -->

<pre>
Title:       Manually validating an ASP .NET user account with a SHA1 hashed password
Author:      Malcolm Swaine | www.malcolmswaine.com
Email:       info@malcolmswaine.com
Member ID:   4887975
Language:    C#, Compact Framework
Platform:    Windows
Technology:  .NET Compact Framework
Level:       Intermediate, Advanced
Description: How to manually validate an ASP .NET Roles and Membership password using SHA1
Section      .NET Compact Framework
SubSection   Windows Mobile
License:     None
</pre>

<!-------------------------------     STEP 2      --------------------------->
<!--  Include download and sample image information.                       --> 

<!-------------------------------     STEP 3      --------------------------->

<!--  Add the article text. Please use simple formatting (<h2>, <p> etc)   --> 

<h2>Introduction</h2>

<p>Recently I came across a situation where I needed to provide the same authentication service provided by the
ASP .NET Roles and Membership provider, but on a mobile device. A mobile device would sync to a back end database
pulling down all the aspNet_XXXX tables. The user of the mobile device would then be able to validate their account 
against the mobile device using their existing ASP .NET Roles and Membership credentials.
</p>


<h2>Using the Code</h2>

<p>The below code demonstrates first checking for a username match, and then comparing the
password hash originally generated by the user to the hash created with the password they
have supplied the program</p>
<p>
In the last lines of the program I persist the user data so that it is available to
the rest of the program.
</p>


<pre>
public bool LogonUser(string userName, string passWord)
{

	Guid userID = Guid.Empty;
	string originalHash = "";
	string saltValue = "";
	DataLayer dataLayer = new DataLayer();

	// first check for a username
	try
	{
		string SQL =
		" Select	aspnet_Membership.UserId, "
		+ "        Password, "
		+ "         PasswordSalt "
		+ " From	aspnet_Membership inner join  "
		+ "         aspnet_Users on aspnet_Membership.UserID = aspnet_Users.UserID "
		+ " Where	LoweredUserName = @p1 ";

		SqlCeCommand sqlCeCommand = new SqlCeCommand(SQL, dataLayer.GetOpenConnection);
		SqlCeParameter param1 = sqlCeCommand.Parameters.Add("p1", System.Data.SqlDbType.NVarChar);
		param1.Value = userName.ToLower();

		SqlCeDataReader reader = sqlCeCommand.ExecuteReader();
		while (reader.Read())
		{
			userID = reader.GetGuid(0);
			originalHash = reader.GetString(1);
			saltValue = reader.GetString(2);
			break;
		}

		reader.Close();
	}
	catch (Exception ex)
	{
		new Logger().Log(ex);
		throw ex;
	}
	finally
	{
		dataLayer.CloseSQLConnection();
	}

	// username exists
	if (userID.CompareTo(Guid.Empty) != 0)
	{

		// compare password hashes
		byte[] bIn = Encoding.Unicode.GetBytes(passWord);
		byte[] bSalt = Convert.FromBase64String(saltValue);
		byte[] bAll = new byte[bSalt.Length + bIn.Length];
		byte[] bRet = null;

		Buffer.BlockCopy(bSalt, 0, bAll, 0, bSalt.Length);
		Buffer.BlockCopy(bIn, 0, bAll, bSalt.Length, bIn.Length);

		HashAlgorithm s = HashAlgorithm.Create("SHA1");

		bRet = s.ComputeHash(bAll);
		string newHash = Convert.ToBase64String(bRet);

		// check the hash in the datbase matched the new hash we generated
		if (originalHash != newHash)
			throw new Exception("Incorrect Username/Password combination. Please try again");

	}
	else
	{
		throw new Exception("Incorrect Username/Password combination. Please try again");
	}

	// store the users credentials in the config object for app instance use
	Config.UserID = userID;
	Config.UserName = userName;
	Config.PassWord = passWord;

	return true;

}

</pre>

<p>
It took me a while to get this, so hopefully this will save someone else scratching their head!
</p>


<!-------------------------------    That's it!   --------------------------->
</body>

</html>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) www.malcolmswaine.com
Thailand Thailand
Professional freelance business software developer working from Thailand.

Comments and Discussions