使用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 )?
$ 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){
//已验证
}
解决方案现在忽略数据库语句的问题,我将回答有关
password_hash
的问题。
简而言之,不,你不这样做,你不想单独存储盐,你应该存储散列和盐,然后使用两者来验证密码。 $ C> password_hash 返回一个包含两者的字符串。
password_hash
函数返回一个字符串,其中包含散列和盐。所以:
$ $ p $ $ $ $ $ $ $ hashAndSalt = password_hash($ password,PASSWORD_BCRYPT);
//将$ hashAndSalt插入数据库,并对用户
然后验证:
//从数据库获取hash + salt,放入$ hashAndSalt变量
//然后验证$ password:
如果(password_verify($ password,$ hashAndSalt)){
//已验证
}
另外,正如注释所示,如果您对安全感兴趣,您可以查看 mysqli
( ext / mysql
在PHP5.5中已弃用),以及关于SQL注入的这篇文章: http://php.net/manual/en/security.database.sql-injection.php
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);
Then I would do:
mysql_query("INSERT INTO users(username,password, salt) VALUES($username, $hash, " . $options['salt']);
To insert into database.
Then to verify:
$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
}
Ignoring the issues with your database statements for now, I'll answer the question regarding 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.
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
Then to verify:
// Fetch hash+salt from database, place in $hashAndSalt variable
// and then to verify $password:
if (password_verify($password, $hashAndSalt)) {
// Verified
}
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屋!