random_bytes - php random_int




Generate a single use token in PHP: random_bytes or openssl_random_pseudo_bytes? (2)

I need to generate a single-use token in PHP. There are two functions available that I can use for this that seem to do the same thing: random_bytes and openssl_random_pseudo_bytes. For example, using random_bytes:

var_dump(bin2hex(random_bytes(12)));

--> string(24) "338f489ec37a2c2b4943905d"

and using openssl_random_pseudo_bytes:

var_dump(bin2hex(openssl_random_pseudo_bytes(12)));

--> string(24) "1c7febea20029bd524fba8e7"

openssl_random_pseudo_bytes is PHP 5.3 and up (so I assume it's been around longer), and random_bytes is PHP 7. I'm using PHP 7 so I can use either.

So is there any major (or minor for that matter) difference between the two? If not, I'm tempted to go with random_bytes simply because it has an easier name ( = code that's easier to read).


openssl_random_pseudo_bytes is part of the OpenSSL extension, which must be explicitly configured and included in the PHP compilation process and requires external dependencies.

random_bytes is new in PHP 7 as the native always-available PHP method to generate random bytes, which chooses its internal source of randomness depending on the platform it's on.

The main reason for introducing random_bytes was that generating pseudo-random data was always a bit of a headache in PHP, requiring developers to be platform-aware and possibly using several different fallback methods depending on which extensions or system-level functions are available. This often led to bugs in individual implementations, which is particularly concerning in security-relevant code. random_bytes simplifies this by providing one function which is always available and uses the best possible source of randomness available. If you can target PHP 7+ exclusively, it should be your go-to method.


According to php manual

random_bytes : Generates cryptographically secure pseudo-random bytes openssl_random_pseudo_bytes : Generate a pseudo-random string of bytes

so main difference is the cryptographically secure

The openssl_random_pseudo_bytes() PHP function calls the RAND_psuedo_bytes() OpenSSL function, which the OpenSSL docs say should only be used for non-cryptographic purposes:

https://paragonie.com/blog/2015/07/how-safely-generate-random-strings-and-integers-in-php





token