PHP7 CSPRNG

Two new functions have been added to generate cryptographically secure integers and strings in a cross platform way: random_bytes() and random_int().

  • random_bytes : Generates cryptographically secure pseudo-random bytes
  • random_int : Generates cryptographically secure pseudo-random integers

random_bytes()

string random_bytes(int $length)

Parametes:

length: The length of the random string that should be returned in bytes.

Returns a string containing the requested number of cryptographically secure random bytes.

  • If an appropriate source of randomness cannot be found, an Exception will be thrown.
  • If invalid parameters are given, a TypeError will be thrown.
  • If an invalid length of bytes is given, an Error will be thrown.

Example

<?php
$bytes = random_bytes(5);
var_dump(bin2hex($bytes));
?>

Output:

string(10) "5f6baa6524"

random_int()

int random_int(int $min, int $max)

Parametes:

min: The lowest value to be returned, which must be PHP_INT_MIN or higher.

max: The highest value to be returned, which must be less than or equal to PHP_INT_MAX.

Returns a cryptographically secure random integer in the range min to max, inclusive

  • If an appropriate source of randomness cannot be found, an Exception will be thrown.
  • If invalid parameters are given, a TypeError will be thrown.
  • If max is less than min, an Error will be thrown.

Example

<?php
var_dump(random_int(100, 999));
var_dump(random_int(-1000, 0));
?>

Output:

int(327)
int(-228)