# Cryptographically Secure Pseudo-Random Number Generator (CSPRNG)

> Section in “New and Extended Functionality › Cryptography and Security” of the book [PHP 7 Explained](https://php7explained.com/) by Sebastian Bergmann and Stefan Priebsch, published by thePHP.cc. The book covers PHP 7.0 to 7.4 and was last updated in November 2020. HTML version: <https://php7explained.com/new-and-extended-functionality/cryptography-and-security/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:

``` php
$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`](https://packagist.org/packages/paragonie/random_compat) is a userland implementation of those two functions.

---

Previous: [OpenSSL](https://php7explained.com/new-and-extended-functionality/cryptography-and-security/openssl/index.html.md) | Next: [Filtering Syslog Messages](https://php7explained.com/new-and-extended-functionality/cryptography-and-security/filtering-syslog-messages/index.html.md)
