Gaurav
Gaurav

Reputation: 597

How to validate user

I am inserting password usinh Salt MD5 method. Below is my code

  protected string GenerateSalt()
{
    byte[] data = new byte[0x10];
    new RNGCryptoServiceProvider().GetBytes(data);
    return Convert.ToBase64String(data);
}
 private string HashPassword(string password, string salt)
 {
     // Create an MD5 hash of the supplied password using the supplied salt as well.
     string sourceText = salt + password;
     ASCIIEncoding asciiEnc = new ASCIIEncoding();
     string hash = null;
     byte[] byteSourceText = asciiEnc.GetBytes(sourceText);
     MD5CryptoServiceProvider md5Hash = new MD5CryptoServiceProvider();
     byte[] byteHash = md5Hash.ComputeHash(byteSourceText);
     foreach (byte b in byteHash)
     {
         hash += b.ToString("x2");
     }

     // Return the hashed password
     return hash;
 }

here I am using to create the password.

 string salt = GenerateSalt();

  string password = HashPassword(txtpassword.Text, salt);

it is working fine and saving the password in database.

But when I try to login in the password doesn't match.

below is my code for matching the password and user id

 string password = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "md5").ToString();
            SqlCommand com11 = new SqlCommand("For_Login1", con);
            com11.CommandType = CommandType.StoredProcedure;
            com11.Parameters.AddWithValue("@User_Id", ddl.SelectedItem.Text);
            com11.Parameters.AddWithValue("@Password", password);

but password didn't match why?

Upvotes: 2

Views: 70

Answers (1)

Nir Alfasi
Nir Alfasi

Reputation: 53545

salt is a final static string (doesn't change) and is usually kept in the DB attached to the hashed password. One convention is to save it as hash(pwd+salt):salt.

You're generating a new salt every time you call generate() because of the following line:

new RNGCryptoServiceProvider().GetBytes(data);

which means that you'll never be able to authenticate.

Upvotes: 1

Related Questions