Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how compare password from database with input user password when password in database hash with sha512 and salt?

thi is my code and dont work:

C#
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Web.Security;
 
 
     
 
public partial class Default2 : System.Web.UI.Page
{
    SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrin  gs["conn"].ConnectionString);
 
 
 
    protected void Page_Load(object sender, EventArgs e)
    {
        Button1.Click += Fire;
 
    }
 
    private void Fire(object sender, EventArgs e)
    {
        int num = 1000;
        string salt = CreateSalt(num);
        string saltpwd = string.Concat(salt, TextBox2.Text);
        CreatePasswordHash(saltpwd);
 
         string str = string.Empty;
              if (Conn.State == ConnectionState.Closed)
                  Conn.Open();
            SqlCommand  Cmd = new SqlCommand("SELECT * FROM Users WHERE  (usr_UserName=@FUserName) ");
              Cmd.Parameters.AddWithValue("@FUserName", TextBox1.Text.Trim());
              Cmd.Connection = Conn;
              SqlDataReader reader = Cmd.ExecuteReader();
              reader.Read();
              if (reader.HasRows)
              {
                  if (!reader.IsDBNull(reader.GetOrdinal("usr_Password"  )))
                  {
                     str = reader.GetString(reader.GetOrdinal("usr_Password")  );
                  }
    
             }
 
              int result = string.Compare(CreatePasswordHash(saltpwd).Trim(), str, true);
               if (result == 0)
                  {
                      Label1.Text = "Good";
                  }
             else
                 {
                     Label1.Text = "Bad";
                 }
    }
 
 
    private string CreateSalt(int size)
    {
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        byte[] buff = new byte[size];
        rng.GetBytes(buff);
        return Convert.ToBase64String(buff);
 
    }
 
    private string CreateSalt1(int size)
    {
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        byte[] buff = new byte[size];
        rng.GetBytes(buff);
        return Convert.ToBase64String(buff);
 
    }
 
    private string CreatePasswordHash(string pwd)
    {
        byte[] Data = System.Text.UTF8Encoding.UTF8.GetBytes(pwd);
        SHA512Managed sha = new SHA512Managed();
        byte[] HashValue = sha.ComputeHash(Data);
        string result = string.Empty;
 
        foreach (var h in HashValue)
            result += string.Format("{0:X}", h);
 
        return result;
    }
 
  
 
 
    protected void Button2_Click(object sender, EventArgs e)
    {
        
    }
Posted
Comments
[no name] 15-Mar-13 9:01am    
"don't work" is not a helpful description of any kind of a problem. Do you call you mechanic and tell him "car broke" and expect he can help you?

Hi,
When the first time the user enters the password, you encrypt them and store them in the database.

When the user access the application, you encrypt the password exactly as before and check against the stored encrypted password.

If the password is same, and the encryption is same then the encrypted values should match.

if in case the salt is pseudo random, as the salt will change each time, keep the salt in the db along the encrypted password. those who hack your system wouldn't know that you have a salt for each user.


Regards
Jegan
 
Share this answer
 
v2
Comments
tree1371 15-Mar-13 9:14am    
My salt is random.

are you say i should save salt for create hash password from user input to database?
Jegan Thiyagesan 16-Mar-13 7:16am    
Yes, because the salt is random, you need to save the salt that used for creating the hash at the first time, so when the next time user login, you use the same salt. Otherwise if you use new salt, the hash will not be same, although the user enters the correct password.
Hello,

You need to store the salt as well in the database. For example the htpasswd.exe from Apache Httpd server stores the salt as first two character (in case of crypt) & as first eight characters (ini case of md5), in the hashed pasword itself.

In your case also you can adopt similar strategy. Your stored password could be generated as shown below
C#
string salt = CreateSalt(num);
string saltpwd = String.Concat(salt, TextBox2.Text);
string strPwdHash = String.concat("$", salt, "$", CreatePasswordHash(saltpwd));

Now when you want to compare the passwords perform similar steps on user input and compare two hashes as shown below
C#
    string strDBPwd = String.Empty;
string strCon = ConfigurationManager.ConnectionStrin  gs["conn"].ConnectionString
SqlConnection Conn = new SqlConnection(strCon);
Conn.Open();
SqlCommand  Cmd = new SqlCommand("SELECT * FROM Users WHERE  (usr_UserName=@FUserName) ");
Cmd.Parameters.AddWithValue("@FUserName", TextBox1.Text.Trim());
Cmd.Connection = Conn;
SqlDataReader reader = Cmd.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
    if (!reader.IsDBNull(reader.GetOrdinal("usr_Password"  )))
    {
        strDBPwd = reader.GetString(reader.GetOrdinal("usr_Password")  );
    }
}
string[] toks = strDBPwd.split(new char[] {'$'}, StringSplitOptions.RemoveEmptyEntries);
string salt = toks[1];
string saltpwd = String.Concat(salt, TextBox2.Text);
string strPwdHash = CreatePasswordHash(saltpwd);
int result = String.Compare(strPwdHash, toks[3], true);


Regards,
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900