Hash encrypting password when inserting into database

风格不统一 提交于 2019-12-02 10:51:05

To hash a string of text you could use a function like this

private string GetHashedText(string inputData)
{ 
    byte[] tmpSource;
    byte[] tmpData;
    tmpSource = ASCIIEncoding.ASCII.GetBytes(inputData);
    tmpData = new MD5CryptoServiceProvider().ComputeHash(tmpSource);
    return Convert.ToBase64String(tmpData);
}

and apply to your user input. Then store the result in the database. At login you reapply the hash function to the typed password and check the result against the stored value.

So in your insert code you write

 sc.Parameters.AddWithValue("@password", GetHashedText(pass.Text));   

and in your check

 ....
 SqlCommand cmd = new SqlCommand("select * from users where userName=@user and password=@pass", con);
 con.Open();
 cmd.Parameters.AddWithValue("@user",user.Text);
 cmd.Parameters.AddWithValue("@pass", GetHashedText(pass.Text));
 SqlDataReader re = cmd.ExecuteReader();
 if (re.Read())
 .....

Remember that Hashing is not reversible, so you cannot retrieve the original password from the hashed text. You apply the Hash function to your text and store it as a base64 string. If your user forgets the password, you need to reset it to a known value. There is no way to tell him the original password.

By the way, why in your check you don't use parameters as you do in the insert code? Never use string concatenation to build sql queries. Even if you're in a hurry to finish the job

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!