如何实现SHA-512、MD5和盐值加密,用于一个密码的全部加密。

21 浏览
0 Comments

如何实现SHA-512、MD5和盐值加密,用于一个密码的全部加密。

这个问题已经在这里有答案

PHP密码的安全哈希与盐

$pass="test"

以上的变量包含了一个名为test的密码。我想使用sha512 md5和盐来哈希这个密码。因为我只发现了盐和sha512的好处,已经知道了md5加密,请问我应该如何操作呢?请提供一个例子,因为我仍然在使用md5。


根据您的评论和答案,我已经得到了以下代码:

$pass="test";
$hashed_pass= openssl_digest($pass, 'sha512');

好的,似乎足够可靠了,但是[salt=\'\']是什么?它会生成随机的盐字符串吗?如果是这样,如何实现呢?

admin 更改状态以发布 2023年5月23日
0
0 Comments

如果您使用的是PHP >= 5.3,函数openssl_digest应该可以解决问题:

echo openssl_digest($pass, 'sha512');
// result
ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff
echo md5($pass);
// result
098f6bcd4621d373cade4e832627b4f6

对于PHP 5.1或5.2,您可以使用hash函数:

echo hash('sha512', $pass);
// result
ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff
echo md5($pass);
098f6bcd4621d373cade4e832627b4f6

0
0 Comments

编辑:由于这个回答似乎仍然引起了一些兴趣,让我引导大家去查看password_hash(),它本质上是crypt()的一个封装,但更容易使用。如果您使用的是PHP<5.5,则有一个名为password_compat的库,它是由同一个人编写的,实际上是从官方文档中链接过去的。

如果您已经在使用crypt(),值得注意的是,password_verify()password_needs_rehash()都支持使用所有crypt()类型的密码,因此完全没有理由不更新!


使用crypt(),它提供了更相对强大的哈希方法。

哈希一个新密码:

// generate a 16-character salt string
$salt = substr(str_replace('+','.',base64_encode(md5(mt_rand(), true))),0,16);
// how many times the string will be hashed
$rounds = 10000;
// pass in the password, the number of rounds, and the salt
// $5$ specifies SHA256-CRYPT, use $6$ if you really want SHA512
echo crypt('password123', sprintf('$5$rounds=%d$%s$', $rounds, $salt));
// output: $5$rounds=10000$3ES3C7XZpT7WQIuC$BEKSvZv./Y3b4ZyWLqq4BfIJzVHQweHqGBukFmo5MI8

比较现有的密码:

// the hash stored for the user
$given_hash = '$5$rounds=10000$3ES3C7XZpT7WQIuC$BEKSvZv./Y3b4ZyWLqq4BfIJzVHQweHqGBukFmo5MI8';
$test_pw = 'password123';
// extract the hashing method, number of rounds, and salt from the stored hash
// and hash the password string accordingly
$parts = explode('$', $given_hash);
$test_hash = crypt($test_pw, sprintf('$%s$%s$%s$', $parts[1], $parts[2], $parts[3]));
// compare
echo $given_hash . "\n" . $test_hash . "\n" . var_export($given_hash === $test_hash, true);
/* output:
$5$rounds=10000$3ES3C7XZpT7WQIuC$BEKSvZv./Y3b4ZyWLqq4BfIJzVHQweHqGBukFmo5MI8
$5$rounds=10000$3ES3C7XZpT7WQIuC$BEKSvZv./Y3b4ZyWLqq4BfIJzVHQweHqGBukFmo5MI8
true */

0