(c) 2002 Visual Studio magazine 
Fawcette Technical Publications

Issue: May 2002
Section: Database Design
Author: Josh Lane

C#	Enable Custom User Authentication 
Listing 1	This code hashes the password stored in the database and compares it with the hashed password sent with the incoming request. A further security and performance measure might be to store the hashed password itself in the database.

private bool DoAuth()
{
string sql = @"select [password] from 
	ReportAuth where username = '" + 
	m_auth.username + "'";
SqlConnection conn = new SqlConnection( m_cs 
	);
SqlCommand cmd = new SqlCommand( sql, conn 
	);

conn.Open();
string dbPassword = ( string ) 
	cmd.ExecuteScalar();
conn.Close();

// indicates no username record in database
if ( dbPassword == null )
{
	return false;
}

ASCIIEncoding aEnc = new ASCIIEncoding();
SHA1Managed sha = new SHA1Managed();
		
byte[] hashedDBPwd = sha.ComputeHash( 
	aEnc.GetBytes( dbPassword ) );

return (aEnc.GetString( m_auth.password ) == 
	aEnc.GetString( hashedDBPwd ) ) ? true : 
	false;
}
