如何为一个密码实现sha 512,md5和salt加密

时间:2014-02-11 20:05:23

标签: php cryptography md5 salt sha512

$pass="test"

上面的变量包含一个名为test的密码。我想使用sha512 md5和salt来哈希这个密码我是怎么做到的,因为我发现只有盐和sha512的好处,我已经知道md5 encryption.please我需要解决方案as我的系统很可贵

请用代码示例解释,因为我仍然附加到md5


从你的意见和答案的理解我已经得到以下代码

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

好吧看起来足够坚固但是[salt ='']是什么? 它会生成一个随机的盐串或其他东西,如果是这样,如何实现它?

2 个答案:

答案 0 :(得分:15)

编辑:由于这个答案似乎仍然引起了一些兴趣,让我引导大家走向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 */

答案 1 :(得分:6)

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

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

echo md5($pass);
// result
098f6bcd4621d373cade4e832627b4f6

使用PHP 5.1或5.2,您可以使用哈希函数:

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

echo md5($pass);
098f6bcd4621d373cade4e832627b4f6