简体   繁体   English

ASP.NET MVC / C#-Linq和哈希密码

[英]ASP.NET MVC / C# - Linq and hashed password

I'm trying to create authentication where all passwords are hashed and salted. 我正在尝试创建身份验证,其中所有密码都经过哈希处理和加盐处理。 First, for simplicity, I tried without salt, here's my linq: 首先,为简单起见,我尝试不加盐,这是我的linq:

var CurrentUser = db.Users
    .Single(u => u.UserName == form["username"] && u.Password.SequenceEqual
               (
                   MD5.Create().ComputeHash
                       (
                           Encoding.UTF8.GetBytes(form["password"])
                       )
               )
          );

Unfortunately, this error occurred: 不幸的是,发生此错误:

The query operator 'SequenceEqual' is not supported. 不支持查询运算符“ SequenceEqual”。

It would help to know where you're getting your user records from (ie what is "db.Users"). 这将有助于知道您从何处获取用户记录(即“ db.Users”)。

Whatever linq provider your using (EF etc) probably doesn't support using SequenceEqual in a query, so you'll need to grab the user record, then check the password: 无论您使用的哪种linq提供程序(EF等)都不支持在查询中使用SequenceEqual,因此您需要获取用户记录,然后检查密码:

var currentUser = db.Users.Single(u => u.UserName == form["username"]);
var hash = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(form["password"]));

var passwordCorrect = currentUser.Password.SequenceEqual(hash);

You may also want to be more explicit in your "u.UserName ==" comparison to make it obvious whether it's case insensitive/ordinal etc. 您可能还希望在“ u.UserName ==”比较中更加明确,以使其区分大小写/普通等。

Edit: Flater's answer will also work fine, but personally I'd rather pull the record back and verify it as you may want to know whether the user actually exists or not (not just whether the username and password are correct) so you can "lock out" accounts or take other (more helpful) action based on a number of incorrect password attempts. 编辑:Flater的答案也可以正常工作,但是我个人希望将记录拉回并进行验证,因为您可能想知道用户是否确实存在(不仅是用户名和密码是否正确),因此您可以“锁定”帐户,或根据许多不正确的密码尝试采取其他(更有帮助的)操作。

LINQ doesn't allow every kind of function/operator in its lambda expressions. LINQ在其lambda表达式中不允许使用各种函数/运算符。 It can be quite annoying at times. 有时可能会很烦人。 I would suggest to find a way in which you can store what you want to check against in a variable, then just checking for 我建议找到一种可以将要检查的内容存储在变量中的方法,然后仅检查

... && u.Password = myVariable);

Why not to get user by name and then compare it's password with salt? 为什么不按名称获取用户,然后将其密码与salt进行比较? Kind of 的种类

var CurrentUser = db.Users
    .FirstOrDefault(u => u.UserName == form["username"]); 
if (CurrentUser == null || !CurrentUser.Password.SequenceEqual(
                   MD5.Create().ComputeHash(
                           Encoding.UTF8.GetBytes(form["password"])))) { ...user of password is incorrect.. }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM