3 namespace Drupal\Component\Utility;
6 * Utility class for cryptographically-secure string handling routines.
13 * Returns a string of highly randomized bytes (over the full 8-bit range).
15 * This function is better than simply calling mt_rand() or any other built-in
16 * PHP function because it can return a long string of bytes (compared to < 4
17 * bytes normally from mt_rand()) and uses the best available pseudo-random
20 * In PHP 7 and up, this uses the built-in PHP function random_bytes().
21 * In older PHP versions, this uses the random_bytes() function provided by
22 * the random_compat library, or the fallback hash-based generator from Drupal
26 * The number of characters (bytes) to return in the string.
29 * A randomly generated string.
31 public static function randomBytes($count) {
33 return random_bytes($count);
35 catch (\Exception $e) {
36 // $random_state does not use drupal_static as it stores random bytes.
37 static $random_state, $bytes;
38 // If the compatibility library fails, this simple hash-based PRNG will
39 // generate a good set of pseudo-random bytes on any system.
40 // Note that it may be important that our $random_state is passed
41 // through hash() prior to being rolled into $output, that the two hash()
42 // invocations are different, and that the extra input into the first one
43 // - the microtime() - is prepended rather than appended. This is to avoid
44 // directly leaking $random_state via the $output stream, which could
45 // allow for trivial prediction of further "random" numbers.
46 if (strlen($bytes) < $count) {
47 // Initialize on the first call. The $_SERVER variable includes user and
48 // system-specific information that varies a little with each page.
49 if (!isset($random_state)) {
50 $random_state = print_r($_SERVER, TRUE);
51 if (function_exists('getmypid')) {
52 // Further initialize with the somewhat random PHP process ID.
53 $random_state .= getmypid();
56 // Ensure mt_rand() is reseeded before calling it the first time.
61 $random_state = hash('sha256', microtime() . mt_rand() . $random_state);
62 $bytes .= hash('sha256', mt_rand() . $random_state, TRUE);
63 } while (strlen($bytes) < $count);
65 $output = substr($bytes, 0, $count);
66 $bytes = substr($bytes, $count);
72 * Calculates a base-64 encoded, URL-safe sha-256 hmac.
75 * Scalar value to be validated with the hmac.
77 * A secret key, this can be any scalar value.
80 * A base-64 encoded sha-256 hmac, with + replaced with -, / with _ and
81 * any = padding characters removed.
83 public static function hmacBase64($data, $key) {
84 // $data and $key being strings here is necessary to avoid empty string
85 // results of the hash function if they are not scalar values. As this
86 // function is used in security-critical contexts like token validation it
87 // is important that it never returns an empty string.
88 if (!is_scalar($data) || !is_scalar($key)) {
89 throw new \InvalidArgumentException('Both parameters passed to \Drupal\Component\Utility\Crypt::hmacBase64 must be scalar values.');
92 $hmac = base64_encode(hash_hmac('sha256', $data, $key, TRUE));
93 // Modify the hmac so it's safe to use in URLs.
94 return str_replace(['+', '/', '='], ['-', '_', ''], $hmac);
98 * Calculates a base-64 encoded, URL-safe sha-256 hash.
100 * @param string $data
101 * String to be hashed.
104 * A base-64 encoded sha-256 hash, with + replaced with -, / with _ and
105 * any = padding characters removed.
107 public static function hashBase64($data) {
108 $hash = base64_encode(hash('sha256', $data, TRUE));
109 // Modify the hash so it's safe to use in URLs.
110 return str_replace(['+', '/', '='], ['-', '_', ''], $hash);
114 * Compares strings in constant time.
116 * @param string $known_string
117 * The expected string.
118 * @param string $user_string
119 * The user supplied string to check.
122 * Returns TRUE when the two strings are equal, FALSE otherwise.
124 public static function hashEquals($known_string, $user_string) {
125 if (function_exists('hash_equals')) {
126 return hash_equals($known_string, $user_string);
129 // Backport of hash_equals() function from PHP 5.6
130 // @see https://github.com/php/php-src/blob/PHP-5.6/ext/hash/hash.c#L739
131 if (!is_string($known_string)) {
132 trigger_error(sprintf("Expected known_string to be a string, %s given", gettype($known_string)), E_USER_WARNING);
136 if (!is_string($user_string)) {
137 trigger_error(sprintf("Expected user_string to be a string, %s given", gettype($user_string)), E_USER_WARNING);
141 $known_len = strlen($known_string);
142 if ($known_len !== strlen($user_string)) {
146 // This is security sensitive code. Do not optimize this for speed.
148 for ($i = 0; $i < $known_len; $i++) {
149 $result |= (ord($known_string[$i]) ^ ord($user_string[$i]));
152 return $result === 0;
157 * Returns a URL-safe, base64 encoded string of highly randomized bytes.
160 * The number of random bytes to fetch and base64 encode.
163 * The base64 encoded result will have a length of up to 4 * $count.
165 * @see \Drupal\Component\Utility\Crypt::randomBytes()
167 public static function randomBytesBase64($count = 32) {
168 return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode(static::randomBytes($count)));