You are here

public static function Crypt::randomBytes in Drupal 8

Returns a string of highly randomized bytes (over the full 8-bit range).

This function is better than simply calling mt_rand() or any other built-in PHP function because it can return a long string of bytes (compared to < 4 bytes normally from mt_rand()) and uses the best available pseudo-random source.

In PHP 7 and up, this uses the built-in PHP function random_bytes(). In older PHP versions, this uses the random_bytes() function provided by the random_compat library, or the fallback hash-based generator from Drupal 7.x.

Parameters

int $count: The number of characters (bytes) to return in the string.

Return value

string A randomly generated string.

Deprecated

in drupal:8.8.0 and is removed from drupal:9.0.0. Use PHP's built-in random_bytes() function instead.

See also

https://www.drupal.org/node/3057191

1 call to Crypt::randomBytes()
CryptTest::testRandomBytes in core/tests/Drupal/Tests/Component/Utility/CryptTest.php
Tests random byte generation.

File

core/lib/Drupal/Component/Utility/Crypt.php, line 36

Class

Crypt
Utility class for cryptographically-secure string handling routines.

Namespace

Drupal\Component\Utility

Code

public static function randomBytes($count) {
  @trigger_error(__CLASS__ . '::randomBytes() is deprecated in Drupal 8.8.0 and will be removed before Drupal 9.0.0. Use PHP\'s built-in random_bytes() function instead. See https://www.drupal.org/node/3057191', E_USER_DEPRECATED);
  return random_bytes($count);
}