Crypt.php 6.0 KB

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