Cryptographically secure random numbers in PHP

PHPCryptographySecurity

Please contribute by voting. Thanks!
3
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:
http://php.net/manual/en/function.openssl-random-pseudo-bytes.php

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:
http://www.codeaddiction.net/articles/4/hash-and-verify-passwords-in-php---the-right-way

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

Your comment

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

Author

Created by Robert Bengtsson [126] Aug 7 '15

Share article

Do you know about

Domain-driven Design (DDD)?

Write an article