说我有一个线性哈希算法:
<?php
$input = "password1";
$round1 = hash('sha512', $input, true);
$round2 = hash('sha512', $round1, true);
echo(base64_encode($round2) . "<br>n");
?>
如何使用hash_init
,hash_update
和hash_final
将其转换为for循环?我现在有一种算法使用这些算法,现在无法将其发布。
刮擦我所说的关闭手柄,这就是hash_copy()
函数的目的。您可能正在寻找:
$algo = 'sha512';
$input = 'password';
$rounds = 1000;
function extend($algo, $rounds, $input) {
$ctx = hash_init($algo);
hash_update($ctx, $input);
for($i=1; $i<$rounds; $i++) {
hash_update($ctx, hash_final(hash_copy($ctx), TRUE));
}
return hash_final($ctx, TRUE);
}
echo base64_encode(extend($algo, $rounds, $input));
但是,这本质上是一起一起,而您的现有代码重新限制了哈希。您将无法获得与使用此方法发布的代码相同的结果。
如果要复制所拥有的代码,则类似:
$algo = 'sha512';
$input = 'password';
$rounds = 1000;
function cycle($algo, $rounds, $input) {
$curhash = reinvent_the_wheel($algo, $input);
for($i=1; $i<$rounds; $i++) {
$curhash = reinvent_the_wheel($algo, $curhash);
}
return $curhash;
}
//equivalent to hash($algo, $input, $true);
function reinvent_the_wheel($algo, $input) {
$ctx = hash_init($algo);
hash_update($ctx, $input);
return hash_final($ctx, TRUE);
}
echo base64_encode(cycle($algo, $rounds, $input)) . "n";
基本上与您发布的代码相同,仅使用 for
loop 添加。