class Crypt (View source)

Utility class for cryptographically-secure string handling routines.

Methods

static string
randomBytes(int $count) deprecated

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

static string
hmacBase64(mixed $data, mixed $key)

Calculates a base-64 encoded, URL-safe sha-256 hmac.

static string
hashBase64(string $data)

Calculates a base-64 encoded, URL-safe sha-256 hash.

static bool
hashEquals(string $known_string, string $user_string) deprecated

Compares strings in constant time.

static string
randomBytesBase64($count = 32)

Returns a URL-safe, base64 encoded string of highly randomized bytes.

Details

static string randomBytes(int $count) deprecated

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

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.

See also

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

static string hmacBase64(mixed $data, mixed $key)

Calculates a base-64 encoded, URL-safe sha-256 hmac.

Parameters

mixed $data

Scalar value to be validated with the hmac.

mixed $key

A secret key, this can be any scalar value.

Return Value

string

A base-64 encoded sha-256 hmac, with + replaced with -, / with _ and any = padding characters removed.

static string hashBase64(string $data)

Calculates a base-64 encoded, URL-safe sha-256 hash.

Parameters

string $data

String to be hashed.

Return Value

string

A base-64 encoded sha-256 hash, with + replaced with -, / with _ and any = padding characters removed.

static bool hashEquals(string $known_string, string $user_string) deprecated

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

Compares strings in constant time.

Parameters

string $known_string

The expected string.

string $user_string

The user supplied string to check.

Return Value

bool

Returns TRUE when the two strings are equal, FALSE otherwise.

See also

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

static string randomBytesBase64($count = 32)

Returns a URL-safe, base64 encoded string of highly randomized bytes.

Parameters

$count

The number of random bytes to fetch and base64 encode.

Return Value

string

A base-64 encoded string, with + replaced with -, / with _ and any = padding characters removed.

See also

Crypt::randomBytes