因此,根据评论,我创建了一个简单的基准来测试各种散列方法需要多长时间。
function bcrypt_salt($cost)
{
return "$2y$" . $cost . "$" . str_replace('+', '.', base64_encode(openssl_random_pseudo_bytes(22))) . '$';
}
function sha512_salt($cost)
{
return "\$6\$rounds=" . $cost . "\$" . openssl_random_pseudo_bytes(16) . '$';
}
$password = "stackoverflow";
$times = 1;
echo "<p>bcrypt method</p>";
for($iters = 10; $iters < 15; ++$iters)
{
$salt = bcrypt_salt(strval($iters));
$pword_crypt = crypt($password, $salt);
$start_time = microtime(true);
for($i = 0; $i < $times; ++$i)
{
crypt($password, $pword_crypt);
}
$end_time = microtime(true);
echo "<p> cost = $iters: " . ($end_time - $start_time) . "</p>";
}
echo "<p>SHA512 method</p>";
for($iters = 1024; $iters < 1000000; $iters *= 2)
{
$salt = sha512_salt(strval($iters));
$pword_crypt = crypt($password, $salt);
$start_time = microtime(true);
for($i = 0; $i < $times; ++$i)
{
crypt($password, $pword_crypt);
}
$end_time = microtime(true);
echo "<p> log2(iters) = ". log($iters,2) . ": " . ($end_time - $start_time) . "</p>";
}
基准测试结果(以秒为单位的时间):
用 i5-m430 在我的笔记本电脑上运行:
bcrypt 方法
成本 = 10:0.11740303039551
成本 = 11:0.23875308036804
成本 = 12:0.46739792823792
成本 = 13:0.96053194999695
成本 = 14:1.8993430137634
SHA512 方法
log2(iters) = 10: 0.0034840106964111
log2(iters) = 11: 0.0077731609344482
log2(iters) = 12: 0.014604806900024
log2(iters) = 13: 0.02855396270752
log2(iters) = 14: 0.068222999572754
log2(iters) = 15: 0.12677311897278
log2(iters) = 16: 0.24734497070312
log2(iters) = 17: 0.54663610458374
log2(iters) = 18: 1.0215079784393
log2(iters) = 19: 2.0223300457001
在所有条件相同的情况下,SHA-512 方法与 bcrypt 相比需要更多的迭代次数才能花费相同的时间。话虽如此,我猜任何至少需要十分之一秒的方法都绰绰有余。