c#asp.net web app sha 256密码验证失败

时间:2015-12-19 21:08:54

标签: c# asp.net login sha256

我在c#asp.net中有一个登录表单,我在数据库中存储用户的哈希密码,如果我再次输入相同的密码,则表示登录失败。这里'textbox2'是密码字段,'g'是哈希密码。我通过sql命令传递'g'但登录总是失败。如果我以纯文本形式传递密码,登录成功,顺便说一句,我已将数据库(visual studio)中的哈希值硬编码为varchar(max)。这是一个问题吗?感谢。

protected void Button1_Click(object sender, EventArgs e)
{
    string g = TextBox2.Text;

    StringBuilder Sb = new StringBuilder();

    using (SHA256 hash = SHA256Managed.Create())
    {
        Encoding enc = Encoding.UTF8;
        Byte[] result = hash.ComputeHash(enc.GetBytes(g));

        foreach (Byte b in result)
            Sb.Append(b.ToString("x2"));
    }

    g = Sb.ToString();

    try
    {
        SqlConnection con = new SqlConnection(@"connectionstring");

        String query = "select * from admin where Id = '" + TextBox1.Text + "'and secret = '" + g + "'";


        SqlCommand myCommand = new SqlCommand(query, con);
       myCommand.Parameters.AddWithValue("@Id", TextBox1.Text);
        myCommand.Parameters.AddWithValue("@secret", g);
        SqlDataReader dbr;
        con.Open();
        dbr = myCommand.ExecuteReader();

        int count = 0;
        while (dbr.Read())
        {
            count = count + 1;
        }
        con.Close();
        if (count == 1)
        {
            Response.Redirect(@"main.aspx");               
        }
        else
        {
            Label3.Visible = true;
        }

    }

    catch (Exception ex)
    {

    }

1 个答案:

答案 0 :(得分:1)

尝试

String query = "select * from admin where Id = @Id and secret = '@secret'";

您可以在MSDN上找到有关SqlCommand和参数的更多信息here