安全密码生成和存储
我正在构建一个登录系统,我想确保我正在编写编写代码以在数据库中生成和存储密码.$options['passwd']
是用户选择作为密码的字符串.
I'm building a login system and I want to be sure I'm writing the write code to generate and store passwords in the db. $options['passwd']
is the string selected as a password by the user.
这是我生成哈希的代码:
This is my code to generate a hash:
public function createPasswd($options) {
$hash_seed = 'm9238asdasdasdad31d2131231231230132k32ka¡2da12sm2382329';
$password = $options['passwd'];
$date = new DateTime();
$timestamp = $date->getTimestamp();
$rand_number = rand($timestamp,$timestamp + pow(91239193912939123912,3));
$rand = pow($rand_number, 12);
$salt = str_shuffle($rand.$hash_seed);
$hash = crypt($password, $salt);
return $hash;
}//End class createPasswd
我只是将哈希值存储在数据库中,然后将其与用户密码进行比较,如下所示:
I just store the hash on the database and then compare it with user's password like the following:
if ($hash == crypt($password, $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
这够强吗?我错过了什么大问题吗?
Is this strong enough? Am I missing some big issue?.
推荐答案
更长的盐并不意味着更好的保护.您没有正确使用 crypt 功能.$salt 参数不应该是一个简单的随机字符串.
Longer salt doesn't mean better protection. You don't use crypt function properly. $salt argument should not be a simple random string.
考虑这个例子:
echo crypt('password one', 'salt lorem ipsum dolor sit amet');
echo crypt('password two', 'salt');
两者都将返回相同的字符串!(sa3tHJ3/KuYvI)
Both will return the same string ! (sa3tHJ3/KuYvI)
查看 http://php.net/crypt 了解更多关于如何正确使用 $salt 的信息.
Check http://php.net/crypt for more information about how to use $salt the correct way.
最好(更安全?)保留一个唯一的 hash_seed 代码端,然后在数据库中只存储一个组合密码和 hash_seed 的字符串的 sha 哈希(或其他算法).
It's also much better (safer?) to keep an unique hash_seed code side and then store in the database only a sha hash (or other algo) of a string combining the password and your hash_seed.
正确的实现是:
define('SECRET_KEY', 'm9238asdasdasdad31d2131231231230132k32ka¡2da12sm2382329'); // longer is better
public function createPasswd($options) {
return hash('sha256', SECRET_KEY . $options['passwd']);
}
检查密码:
if ($stored_hash == hash('sha256', SECRET_KEY . $password) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
sha256 可以替换为您系统上的任何可用算法.获取完整列表:
sha256 can be replaced with any available algorithms on your system. Get the complete list with :
var_dump(hash_algos());
相关文章