Cryptographically secure random numbers in PHP


Please contribute by voting. Thanks!
If you are to create a random number, you need to carefully consider the security implications. Random numbers that are to be used in security, cryptography or similar areas must be created the right way. Failing to do this will make your application vulnerable.

This is how you create secure random numbers in PHP:

Alternative 1 - use PHP's built in support for OpenSSL

The following function will return N number of securely generated random bytes and is built in to PHP since 5.3.0:
openssl_random_pseudo_bytes(8, $ret);
The first parameter decides how many random bytes that will be returned. The second parameter should return TRUE, which it will if the algorithm used by OpenSSL counts as secure.

Refer to the functions documentation here:

Alternative 2 - use your system's built in support

Both Linux/Unix (/dev/urandom) and Windows (crypto-api) have good support for generating securely generated random numbers.

Final notes

A special case is salting the hash when creating a password hash. Do not do this yourself. PHP as excellent functionality that helps you with this:

Article created: Aug 7 '15. Edited Aug 13 '15.

Your comment

You need to sign up / log in to comment this article


Created by Robert Bengtsson [126] Aug 7 '15

Share article

Do you know about


Write an article