为什么我不能通过C#中的数据库中的sha1查询加密密码

时间:2015-07-18 09:59:06

标签: c# sql-server encryption sha1

我的SQL Sever数据库中有一条记录,如:

Use_Name: admin1 
// see comment on answer below: this hash is wrong. 
Use_Password: 7c4a8d09ca3762af61e59520943dc26494f8941b7c4a8d09ca3762af61e59520943dc26494f8941b
reverses -> 123456

我的问题是:加密后的密码无法通过

找到
var user = db.Users.Where(b => b.Use_Name == name)
                   .Where(b => b.Use_Password == passSHA1)
                   .ToList<User>();

public bool Login(string name, string password)
{
    try
    {
       string passSHA1;
       passSHA1 = ToSHA1(password);

       var user = db.Users.Where(b => b.Use_Name == name)
                          .Where(b => b.Use_Password == passSHA1)
                          .ToList<User>();

       if (user.Any())
       {
          return true;
       }
       else
       {
          return false;
       }
    }
    catch (Exception ex)
    {
        return false;
        throw new Exception("UserBO.Login" + ex.ToString());
    }
}

这是我转换为SHA1函数:

private string ToSHA1 (string pass) {
    SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
    byte[] bs = System.Text.Encoding.UTF8.GetBytes(pass);
    bs = sha1.ComputeHash(bs);
    System.Text.StringBuilder s = new System.Text.StringBuilder();

    foreach (byte b in bs) {
         s.Append(b.ToString("x1").ToLower());
    }

    pass = s.ToString();
    return pass;
}

找不到任何记录。我该如何解决这个问题。

非常感谢!

1 个答案:

答案 0 :(得分:1)

我建议您检查将记录放入数据库的方法,因为ToSHA1("123456") == "7c4a8d09ca3762af61e59520943dc26494f8941b7c4a8d09ca3762af61e59520943dc26494f8941b"false

看起来像某种复制粘贴问题,因为ToSHA("123456")几乎是哈希的一半:7c4a8d9ca3762af61e59520943dc26494f8941b