store the username-password in the Database and authenticate users securely

Most of people wonders about how username-passwords are being stored in the database. After reading this articles you will see that it is very simple but very secure mechanism to store the username - passwords key combination in the database and authenticate the user.

//You will need to add following two methods in your application:
using System.Security.Cryptography;
using System.Web.Security;

//Below procedure will create any random strigs of given size. Basically this type of algorithm reads the memory at random locations to form
//the complete random string each time
private static string CreateSalt(int size)
{
// Generate a cryptographic random number using the cryptographic
// service provider
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);
}

//The salt created in above function will be appended to the real password
//and again SHA1 algorithm will be used to generate the hash which will eventually stored in database
private static string CreatePasswordHash(string pwd, string salt)
{
string saltAndPwd = String.Concat(pwd, salt);
string hashedPwd =
FormsAuthentication.HashPasswordForStoringInConfigFile(
saltAndPwd, "SHA1");
hashedPwd = String.Concat(hashedPwd, salt);
return hashedPwd;
}

//You will need to create stored procedure to insert the user-password details:

CREATE PROCEDURE RegisterUser
@userName varchar(20),
@passwordHash varchar(40)
AS
INSERT INTO Users VALUES(@userName, @passwordHash)

//Below function will create salt and password hash to build the secure and encrypted password.

int saltSize = 10; //You can set this size to big number to have more secure password hash
string salt = CreateSalt(saltSize);
string passwordHash = CreatePasswordHash(txtPassword.Text,salt);
try
{
StoreAccountDetails( txtUserName.Text, passwordHash);
}
catch(Exception ex)
{
lblMessage.Text = ex.Message;
}

//StoreAccountDetails function will connect to your SQL database
//it will call the above stored procedure to store the user-passwordhash into the database

private void StoreAccountDetails( string userName,
string passwordHash )
{
SqlConnection conn = new SqlConnection( "Server=(local);" +
"Integrated
Security=SSPI;" +
"database="YourDatabseName");

SqlCommand cmd = new SqlCommand("RegisterUser", conn );
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter sqlParam = null;
//Usage of Sql parameters also helps avoid SQL Injection attacks.
sqlParam = cmd.Parameters.Add("@userName", SqlDbType.VarChar,20);
sqlParam.Value = userName;

sqlParam = cmd.Parameters.Add("@passwordHash ", SqlDbType.VarChar,40);
sqlParam.Value = passwordHash;

try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch( Exception ex )
{
// Code to check for primary key violation (duplicate accountname)
// or other database errors omitted for clarity
throw new Exception("Exception adding account. " + ex.Message);
}
finally
{
conn.Close();
}
}

//To verify the username - password when user entered the login info

//Create below stored procedure

CREATE PROCEDURE LookupUser
@userName varchar(20)
AS
SELECT PasswordHash
FROM Users
WHERE UserName = @userName

//Below function will call above stored procedure and returns true if user is authenticated
private bool VerifyPassword(string suppliedUserName,
string suppliedPassword )
{
bool passwordMatch = false;
SqlConnection conn = new SqlConnection( "Server=(local);" +
"Integrated
Security=SSPI;" +
"database=YourDatabaseName");
SqlCommand cmd = new SqlCommand( "LookupUser", conn );
cmd.CommandType = CommandType.StoredProcedure;
//Usage of Sql parameters also helps avoid SQL Injection attacks.
SqlParameter sqlParam = cmd.Parameters.Add("@userName",
SqlDbType.VarChar,
20);
sqlParam.Value = suppliedUserName;
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read(); // Advance to the one and only row
// Return output parameters from returned data stream
string dbPasswordHash = reader.GetString(0);
int saltSize = 10;
string salt =
dbPasswordHash.Substring(dbPasswordHash.Length - saltSize);
reader.Close();
// Now take the password supplied by the user
// and generate the hash.
string hashedPasswordAndSalt =
CreatePasswordHash(suppliedPassword, salt);
// Now verify them.
passwordMatch = hashedPasswordAndSalt.Equals(dbPasswordHash);
}
catch (Exception ex)
{
throw new Exception("Execption verifying password. " +
ex.Message);
}
finally
{
conn.Close();
}
return passwordMatch;
}

Regards,
Megha
By Perry    Popularity  (2824 Views)