I need a replacement for PHP's rand()
function that uses a cryptographically strong random number generator.
The openssl_random_pseudo_bytes()
function gets you access to the strong random number generator, but it outputs its data as a byte string. Instead, I need an integer between 0 and X.
I imagine the key is to get the output of openssl_random_pseudo_bytes()
into an integer, then you can do any math on it that you need to. I can think of a few "brute force" ways of converting from a byte string to an integer, but I was hoping for something ... elegant.
Since PHP 7 is out now, the easiest way to solve this problem is to replace all instances of
mt_rand
withrandom_int
.(Assuming you've upgraded, that is.)
The manual page for
openssl_random_pseudo_bytes()
has an example I think you want. You can just callbin2hex()
on the output ofopenssl_random_pseudo_bytes()
to convert to a hexadecimal number, thenhexdec()
on that value to convert to decimal.At that point you can do whatever math you want to get a value in the range you need. The other (cheater) option you might have is to run a system command to generate a random number - there are a few good options for random number generators for various operating systems available online.
Using provided suggestions, I've created a drop-in replacement for rand() using OpenSSL. I'll include it here for posterity.
The $pedantic option gives bias-free results by starting over when results won't be evenly distributed across the possible range.
well, just use hexdec on the result of openssl_random_pseudo_bytes and you will get your integer. It is as elegant as it gets :)
The easiest way to do this (and the most secure out of all the options here) is to use CryptoLib which has a randomInt function that provides a drop-in replacement for rand.
First download CryptoLib from and stick it in your project: https://github.com/IcyApril/CryptoLib
Two, drop in this code. replace path/to/ with the directory of cryptolib.php and the min max with your minimum and maximum numbers:
The CryptoLib full documentation is at: https://cryptolib.ju.je/