/core/lib/Drupal/Component/Utility/Crypt.php

https://gitlab.com/geeta7/drupal · PHP · 193 lines · 74 code · 20 blank · 99 comment · 15 complexity · 0702d400d22f2cc958a41a7931dc4caa MD5 · raw file

  1. <?php
  2. /**
  3. * @file
  4. * Contains \Drupal\Component\Utility\Crypt.
  5. */
  6. namespace Drupal\Component\Utility;
  7. /**
  8. * Utility class for cryptographically-secure string handling routines.
  9. *
  10. * @ingroup utility
  11. */
  12. class Crypt {
  13. /**
  14. * Returns a string of highly randomized bytes (over the full 8-bit range).
  15. *
  16. * This function is better than simply calling mt_rand() or any other built-in
  17. * PHP function because it can return a long string of bytes (compared to < 4
  18. * bytes normally from mt_rand()) and uses the best available pseudo-random
  19. * source.
  20. *
  21. * @param int $count
  22. * The number of characters (bytes) to return in the string.
  23. *
  24. * @return string
  25. * A randomly generated string.
  26. */
  27. public static function randomBytes($count) {
  28. // $random_state does not use drupal_static as it stores random bytes.
  29. static $random_state, $bytes;
  30. $missing_bytes = $count - strlen($bytes);
  31. if ($missing_bytes > 0) {
  32. // openssl_random_pseudo_bytes() will find entropy in a system-dependent
  33. // way.
  34. if (function_exists('openssl_random_pseudo_bytes')) {
  35. $bytes .= openssl_random_pseudo_bytes($missing_bytes);
  36. }
  37. // If OpenSSL is not available, we can use mcrypt. On Windows, this will
  38. // transparently pull from CryptGenRandom. On Unix-based systems, it will
  39. // read from /dev/urandom as expected.
  40. elseif (function_exists(('mcrypt_create_iv')) && defined('MCRYPT_DEV_URANDOM')) {
  41. $bytes .= mcrypt_create_iv($count, MCRYPT_DEV_URANDOM);
  42. }
  43. // Else, read directly from /dev/urandom, which is available on many *nix
  44. // systems and is considered cryptographically secure.
  45. elseif ($fh = @fopen('/dev/urandom', 'rb')) {
  46. // PHP only performs buffered reads, so in reality it will always read
  47. // at least 4096 bytes. Thus, it costs nothing extra to read and store
  48. // that much so as to speed any additional invocations.
  49. $bytes .= fread($fh, max(4096, $missing_bytes));
  50. fclose($fh);
  51. }
  52. // If we couldn't get enough entropy, this simple hash-based PRNG will
  53. // generate a good set of pseudo-random bytes on any system.
  54. // Note that it may be important that our $random_state is passed
  55. // through hash() prior to being rolled into $output, that the two hash()
  56. // invocations are different, and that the extra input into the first one -
  57. // the microtime() - is prepended rather than appended. This is to avoid
  58. // directly leaking $random_state via the $output stream, which could
  59. // allow for trivial prediction of further "random" numbers.
  60. if (strlen($bytes) < $count) {
  61. // Initialize on the first call. The contents of $_SERVER includes a mix
  62. // of user-specific and system information that varies a little with
  63. // each page.
  64. if (!isset($random_state)) {
  65. $random_state = print_r($_SERVER, TRUE);
  66. if (function_exists('getmypid')) {
  67. // Further initialize with the somewhat random PHP process ID.
  68. $random_state .= getmypid();
  69. }
  70. $bytes = '';
  71. }
  72. do {
  73. $random_state = hash('sha256', microtime() . mt_rand() . $random_state);
  74. $bytes .= hash('sha256', mt_rand() . $random_state, TRUE);
  75. } while (strlen($bytes) < $count);
  76. }
  77. }
  78. $output = substr($bytes, 0, $count);
  79. $bytes = substr($bytes, $count);
  80. return $output;
  81. }
  82. /**
  83. * Calculates a base-64 encoded, URL-safe sha-256 hmac.
  84. *
  85. * @param mixed $data
  86. * Scalar value to be validated with the hmac.
  87. * @param mixed $key
  88. * A secret key, this can be any scalar value.
  89. *
  90. * @return string
  91. * A base-64 encoded sha-256 hmac, with + replaced with -, / with _ and
  92. * any = padding characters removed.
  93. */
  94. public static function hmacBase64($data, $key) {
  95. // $data and $key being strings here is necessary to avoid empty string
  96. // results of the hash function if they are not scalar values. As this
  97. // function is used in security-critical contexts like token validation it
  98. // is important that it never returns an empty string.
  99. if (!is_scalar($data) || !is_scalar($key)) {
  100. throw new \InvalidArgumentException('Both parameters passed to \Drupal\Component\Utility\Crypt::hmacBase64 must be scalar values.');
  101. }
  102. $hmac = base64_encode(hash_hmac('sha256', $data, $key, TRUE));
  103. // Modify the hmac so it's safe to use in URLs.
  104. return str_replace(['+', '/', '='], ['-', '_', ''], $hmac);
  105. }
  106. /**
  107. * Calculates a base-64 encoded, URL-safe sha-256 hash.
  108. *
  109. * @param string $data
  110. * String to be hashed.
  111. *
  112. * @return string
  113. * A base-64 encoded sha-256 hash, with + replaced with -, / with _ and
  114. * any = padding characters removed.
  115. */
  116. public static function hashBase64($data) {
  117. $hash = base64_encode(hash('sha256', $data, TRUE));
  118. // Modify the hash so it's safe to use in URLs.
  119. return str_replace(['+', '/', '='], ['-', '_', ''], $hash);
  120. }
  121. /**
  122. * Compares strings in constant time.
  123. *
  124. * @param string $known_string
  125. * The expected string.
  126. * @param string $user_string
  127. * The user supplied string to check.
  128. *
  129. * @return bool
  130. * Returns TRUE when the two strings are equal, FALSE otherwise.
  131. */
  132. public static function hashEquals($known_string, $user_string) {
  133. if (function_exists('hash_equals')) {
  134. return hash_equals($known_string, $user_string);
  135. }
  136. else {
  137. // Backport of hash_equals() function from PHP 5.6
  138. // @see https://github.com/php/php-src/blob/PHP-5.6/ext/hash/hash.c#L739
  139. if (!is_string($known_string)) {
  140. trigger_error(sprintf("Expected known_string to be a string, %s given", gettype($known_string)), E_USER_WARNING);
  141. return FALSE;
  142. }
  143. if (!is_string($user_string)) {
  144. trigger_error(sprintf("Expected user_string to be a string, %s given", gettype($user_string)), E_USER_WARNING);
  145. return FALSE;
  146. }
  147. $known_len = strlen($known_string);
  148. if ($known_len !== strlen($user_string)) {
  149. return FALSE;
  150. }
  151. // This is security sensitive code. Do not optimize this for speed.
  152. $result = 0;
  153. for ($i = 0; $i < $known_len; $i++) {
  154. $result |= (ord($known_string[$i]) ^ ord($user_string[$i]));
  155. }
  156. return $result === 0;
  157. }
  158. }
  159. /**
  160. * Returns a URL-safe, base64 encoded string of highly randomized bytes.
  161. *
  162. * @param $byte_count
  163. * The number of random bytes to fetch and base64 encode.
  164. *
  165. * @return string
  166. * The base64 encoded result will have a length of up to 4 * $byte_count.
  167. *
  168. * @see \Drupal\Component\Utility\Crypt::randomBytes()
  169. */
  170. public static function randomBytesBase64($count = 32) {
  171. return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode(static::randomBytes($count)));
  172. }
  173. }