Cryptographically Secure Pseudo-Random Number Generator (CSPRNG)
Previous versions of PHP did not provide an easy to use mechanism for accessing cryptographically strong random numbers in user-land. This was particularly true if the code was supposed to be portable, i.e. run on Linux, macOS, and Windows all the same.
One had to choose between
openssl_random_pseudo_bytes()
– which required OpenSSL
support to be enabled and does not even guarantee cryptographically
secure values – , mcrypt_create_iv()
– adding a
dependency to the mcrypt
extension which is deprecated
– or read some bytes from /dev/*random
devices in case
the operating system of choice was providing those. Some considered
even using uniqid()
as a potential source, being
unaware of the fact that uniqid()
is even worse and
does not provide cryptographically strong values as it is merely a
fancy obfuscated timestamp.
PHP 7 addresses this issue by adding the two new functions
random_bytes()
and random_int()
to provide
an easy to use and portable implementation of a CSPRNG:
$bytes = random_bytes(10);
$int = random_int(0,100);
While the first will generate a 10 byte long random string – which may very well include non-printable characters –, the second will generate a random integer value within the given range.
For backwards compatibility with PHP 5, paragonie/random_compat
is a userland implementation of those two functions.