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.
Aucun commentaire:
Enregistrer un commentaire