WEB DEVELOPER SITE
PYTHON
 

PHP 7 CSPRNG




Php 7 now introduce new generate cryptographically secure integers and strings in a cross platform

  • random_bytes() generates cryptographically secure pseudo-random bytes
  • random_int() generates cryptographically secure pseudo-random integers.

What is random_bytes()

Mainly used for encryption such as when generating key and initialization vectors.

Syntex

 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(7); var_dump(bin2hex($bytes));
?>
Run example »

Answer

 string(14) "b257904a169627" 





What is random_int()

random_int — Generates cryptographically secure pseudo-random integers

Syntex

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 invalid parameters are given, a TypeError will be thrown.
  • If max is less than min, an Error will be thrown.
<?php
var_dump(random_int(100, 1000));
var_dump(random_int(-100, 0));
?>
Answer

int(963) int(-43)