Hash encrypting password when inserting into database

后端 未结 1 487
野的像风
野的像风 2021-01-28 19:49

I\'m doing an application for school and I\'m in need of help in encrypting passwords when inserting them into my users database.I\'m programming in c# programming language and

相关标签:
1条回答
  • 2021-01-28 20:14

    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

    0 讨论(0)
提交回复
热议问题