使用 PHP 5.5 的 password_hash 和 password_verify 函数 [英] Using PHP 5.5's password_hash and password_verify function
问题描述
假设我想为用户存储密码,这是否是使用 PHP 5.5 的 password_hash()
函数(或 PHP 5.3.7+ 的此版本:https://github.com/ircmaxell/password_compat)?
Say I wanted to store a password for a user, would this be the right way to do it with PHP 5.5's password_hash()
function (or this version for PHP 5.3.7+: https://github.com/ircmaxell/password_compat)?
$options = array("cost" => 10, "salt" => uniqid());
$hash = password_hash($password, PASSWORD_BCRYPT, $options);
然后我会这样做:
mysql_query("INSERT INTO users(username,password, salt) VALUES($username, $hash, " . $options['salt']);
插入数据库.
然后验证:
$row = mysql_fetch_assoc(mysql_query("SELECT salt FROM users WHERE id=$userid"));
$salt = $row["salt"];
$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 10, "salt" => $salt));
if (password_verify($password, $hash) {
// Verified
}
推荐答案
暂时忽略你的数据库语句的问题,我来回答关于password_hash
的问题.
Ignoring the issues with your database statements for now, I'll answer the question regarding password_hash
.
简而言之,不,这不是你做的方式.您不想单独存储盐,您应该同时存储哈希和盐,然后使用两者来验证密码.password_hash
返回包含两者的字符串.
In short, no, that is not how you do it. You do not want to store the salt alone, you should be storing both the hash and salt, and then using both to verify the password. password_hash
returns a string containing both.
password_hash
函数返回一个包含哈希值和盐值的字符串.所以:
The password_hash
function returns a string that contains both the hash and the salt. So:
$hashAndSalt = password_hash($password, PASSWORD_BCRYPT);
// Insert $hashAndSalt into database against user
然后验证:
// Fetch hash+salt from database, place in $hashAndSalt variable
// and then to verify $password:
if (password_verify($password, $hashAndSalt)) {
// Verified
}
此外,正如评论所暗示的,如果您对安全感兴趣,您可能需要查看 mysqli
(ext/mysql
在 PHP5.5 中已弃用),还有这篇关于 SQL 注入的文章:http://php.net/manual/en/security.database.sql-injection.php
Additionally, as the comments suggest, if you're interested in security you may want to look at mysqli
(ext/mysql
is deprecated in PHP5.5), and also this article on SQL injection: http://php.net/manual/en/security.database.sql-injection.php
这篇关于使用 PHP 5.5 的 password_hash 和 password_verify 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!