Question

Say I have a linear hashing algorithm:

<?php
    $input = "password1";

    $round1 = hash('sha512', $input, true);
    $round2 = hash('sha512', $round1, true);

    echo(base64_encode($round2) . "<br>\n");
?>

How would I convert this to a for loop using hash_init, hash_update, and hash_final? I have a algorithm using these in a for loop right now, but I am unable to post it.

Était-ce utile?

La solution

Scratch what I said about closing the handle, that's what hash_copy() function is for. You're probably looking for something like:

$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));

But this essentially appends the hashes together, whereas your existing code re-hashes the hashes. You will not be able to get the same result as the code you posted using this method.

If you want to replicate the code you have, then something like:

$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";

Which is basically the same code as you posted, just with a for loop added.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top