问题描述
我正在测试 sha1 和 md5 的几种组合:
i'm testing several combinations of sha1 and md5:
<?php
$test = 'fail test';
echo nl2br ("Text: $test\n");
echo nl2br ("md5: ".md5($test)."\nsha1: ".sha1($test)."\nsha1(md5): ".sha1(md5($test))."\nmd5(sha1): ".md5(sha1($test)));
?>
输出:
Text: fail test
md5: 748410d0085967c496d54dd8fcbecc96
sha1: d730125e8cb8576459173655148fb6896ef44c09
sha1(md5): faa3ebeecfec45e509e93e6b245a69e2a78785ea
md5(sha1): b48e89b85c350c91eb302c1de96d4249
哪个更好,或者用户使用其他什么?如果是,那又如何?
Which one better, or maybe user something else ? If yes, what then ?
推荐答案
散列散列不会增加额外的安全性.(事实上,如果这个人有一个哈希值查找表,情况可能会更糟.)
Hashing a hash adds no extra security. (In fact, it might make it worse if the person has a hash-of-hash lookup table.)
最好的散列将是在没有任何漏洞的情况下执行计算成本最高的散列.我会用至少 sha-256 来散列密码.
The best hash will be the one that is computationally the most expensive to perform without any vulnerabilities. I would hash passwords with at least sha-256.
始终使用加盐密钥对密码进行哈希处理.这个密钥应该是每个密码唯一的.它不需要私下存储.加盐密码的目的是让获得您数据库访问权限的黑客不能简单地将哈希与对应于常见密码的已知哈希列表进行比较.相反,他必须尝试通过尝试所有可能的密码来暴力破解密码.
Always hash your passwords with a salted key. This key should be unique per password. It doesn't need to be stored privately. The purpose of a salted password is that the hacker who gained access to your database cannot simply compare the hash with a known list of hashes that correspond to common passwords. Instead, he must try to brute force the password by trying every possible password.
通过为每个密码使用唯一的盐,您可以保证数据库中的每个哈希值都不同,即使它们使用相同的密码.
By using a unique salt per password, you guarantee that each hash in the database is different, even if they use the same password.
要为密码加盐,只需创建一个随机字符串并将其附加到密码中.这是一个带有 48 位盐和 sha-256 的示例哈希:
To salt a password, simply create a random string of characters and append it to the password. Here's a sample hash with a 48-bit salt and sha-256:
function make_password($password)
{
# random 48-bit salt (8 chars when base64 encoded)
$salt = base64_encode(pack('S3', mt_rand(0,0xffff), mt_rand(0,0xffff), mt_rand(0, 0xffff)));
return $salt.hash('sha256', $salt.$password);
}
function check_password($password, $hash)
{
$salt = substr($hash, 0, 8);
return hash('sha256', $salt.$password) == substr($hash, 8);
}
$password = 'password';
$hash = make_password('password');
echo $hash."\n";
var_dump(check_password('password', $hash));
var_dump(check_password('wrong', $hash));
每次运行时,哈希值都会不同.要验证密码,请选择用户名匹配的行,然后调用 check_password($password_from_user, $hash_from_db)
.
Every time you run it, the hash will be different. To validate a password, you select the row where the username matches, and then call check_password($password_from_user, $hash_from_db)
.
这是一个示例输出:
AzrD1jZzc693714a43ad5dfd4106c0a620ef23ff9915070711fa170a6670b8164862b496
bool(true)
bool(false)
如果您愿意,可以使用更大的盐或更强的散列算法.但至少,我会使用上面类似的东西.
You can use a larger salt or a stronger hashing algorithm if you prefer. But at minimum, I would use something like the above.
这篇关于php用户密码保护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!