PHP 7 - CSPRNG


Advertisements

In PHP 7, following two new functions are introduced to generate cryptographically secure integers and strings in a cross platform way.

  • random_bytes() − Generates cryptographically secure pseudo-random bytes.

  • random_int() − Generates cryptographically secure pseudo-random integers.

random_bytes()

random_bytes() generates an arbitrary-length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors.

Syntax

string random_bytes ( int $length )

Parameters

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

Return Values

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

Errors/Exceptions

  • 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);
   print(bin2hex($bytes));
?>

It produces the following browser output −

54cc305593

random_int()

random_int() generates cryptographic random integers that are suitable for use where unbiased results are critical.

Syntax

int random_int ( int $min , int $max )

Parameters

  • 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.

Return Values

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

Errors/Exceptions

  • 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
   print(random_int(100, 999));
   print("");
   print(random_int(-1000, 0));
?>

It produces the following browser output −

614
-882
Advertisements