phprandomhashrecreate

Recreateable random number in php


I need to get a "random" number (0-9) based on a string, so that it can be recreated. My solution was to use SHA512 and take the 2nd number, like this:

$random = filter_var(hash('sha512', 'STRING COMES HERE'), FILTER_SANITIZE_NUMBER_INT)[1];

I want to know if this is accurate and not predictable. I need this random number to decide between two options. I did a test to see if the numbers gave me a 50/50 ratio.

$option1 = 0;
$option2 = 0;
$times = 1000000; // amount of iterations

for($i = 0; $i < $times; $i++) {
    $result = filter_var(hash('sha512', rand()), FILTER_SANITIZE_NUMBER_INT)[1];
    if($result < 5) {
        $option1++;
    }
    else {
        $option2++;
    }
}

echo "Option 1: ".($option1/$times * 100)."%";
echo "</p>Option 2: ".($option2/$times * 100)."%";

and this was the outcome

Option 1: 49.9207%

Option 2: 50.0793%

I need to know if it's safe to use this method, even though the outcome seems pretty accurate.


Solution

  • Cryptographically secure hash functions (and the "S" in SHA stands for "Secure") have the property that their output is effectively indistinguishable from random output. Changing a single bit of the input should on average flip half of the output bits in a way that looks completely random. Anything less than that would introduce a vulnerability. Thus, you are almost guaranteed to have a uniform distribution. But -- what do you mean by "safe"? Without knowing about what, if anything, you are trying to secure against it is impossible to answer the question "I need to know if it's safe to use this method". As a general rule of thumb -- if you really have to ask then then answer is probably "no".