Generate cryptographically secure random numbers in php

后端 未结 16 1683
孤街浪徒
孤街浪徒 2020-11-29 07:39

PHP\'s rand() function doesn\'t give good random numbers. So I started to use mt_rand() which is said to give better results. But how good are thes

16条回答
  •  囚心锁ツ
    2020-11-29 08:18

    Although the answer was accepted years ago, I'll re-reopen it.

    Since all this randomness depends on the system time, let's mess with the system time too! The amount of time an operation takes on the computer is actually rather variable (especially if other stuff is happening on that server), so if we take advantage of that with microtime... (couldn't find any portable nanotime commands)

    $a='';
    for (int $i=0; $i<9001; $i++)
    {
        usleep(mt_rand(1000,10000));//Also eliminates timing attacks... possibly?
        $a=hash('SHA512',$a.uniqid(mt_rand().microtime(),true));
    }
    echo $a;
    

    Nominally this has 207023 bits of entropy, since you're adding another 23 bits every iteration, but there's a lot of interdependencies, so it's probably a few orders of magnitude less. Still pretty good.

    Do you know of any operations on PHP that take a really random amount of time? Like... HTTP-requesting some website (other than RANDOM.org) and measuring the time it takes?

提交回复
热议问题