-1

我有一个包含 3 列的表:电子邮件、通行证、盐

当用户登录时,我会收到电子邮件并通过 - 但不是盐。如何使用单个查询验证用户?

这就是我想要做的(但显然有缺陷):

$query = "SELECT users.salt FROM users WHERE email='$email' AND password='{hash_hmac('sha256', $password, users.salt)}'";

谢谢!

4

3 回答 3

3

在您尝试使用它来创建哈希时,您没有数据库中的用户盐。

当使用基于盐的哈希时,您通常会从数据库中选择用户盐和密码(以及您以后可能需要的其他信息,例如用户 ID)。并在您的应用程序中进行哈希比较。

于 2013-05-02T23:56:16.553 回答
1

您不能在花括号中使用函数:{hash_mac( ...

用这个:

$query  = "SELECT users.salt FROM users WHERE email='$email' AND password='";
$query .= hash_hmac('sha256', $password, users.salt) . "'";

但是还有一个问题。users.salt在 PHP 上下文中将不可用。你必须先得到它:

// get salt (pseudo code):
$salt = db_query("SELECT users.salt FROM users WHERE email = '$email'");

// use it in the query
$query  = "SELECT users.salt FROM users WHERE email='$email' AND password='";
$query .= hash_hmac('sha256', $password, $salt) . "'";

题外话:我觉得这很有趣,这里有一个基本示例,如何在花括号中使用函数。我rand()在示例中使用了该函数:

$rand = 'rand';
echo "{$rand()}";
于 2013-05-02T23:57:27.957 回答
0

You're mixing PHP and SQL here in a way that can't be done.

This is a really awful way of doing this:

SELECT * FROM users
  WHERE email=:email
    AND SHA2(CONCAT(:password, salt), 256)=:hashed

Note that this will result in a row scan of all user records in the database and will perform terribly. That's why this approach is never used in production code.

What you're supposed to do is fetch the salt for a particular email, hash the supplied password with it, and then compare the result to the saved hashed value:

SELECT * FROM users WHERE email=:email

If you used a library for this instead of writing your own, you probably wouldn't be having these issues. At least you're not using MD5.

于 2013-05-03T00:02:54.517 回答