comparison core/lib/Drupal/Component/Utility/Crypt.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 namespace Drupal\Component\Utility;
4
5 /**
6 * Utility class for cryptographically-secure string handling routines.
7 *
8 * @ingroup utility
9 */
10 class Crypt {
11
12 /**
13 * Returns a string of highly randomized bytes (over the full 8-bit range).
14 *
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
18 * source.
19 *
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
23 * 7.x.
24 *
25 * @param int $count
26 * The number of characters (bytes) to return in the string.
27 *
28 * @return string
29 * A randomly generated string.
30 */
31 public static function randomBytes($count) {
32 try {
33 return random_bytes($count);
34 }
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();
54 }
55 $bytes = '';
56 // Ensure mt_rand() is reseeded before calling it the first time.
57 mt_srand();
58 }
59
60 do {
61 $random_state = hash('sha256', microtime() . mt_rand() . $random_state);
62 $bytes .= hash('sha256', mt_rand() . $random_state, TRUE);
63 } while (strlen($bytes) < $count);
64 }
65 $output = substr($bytes, 0, $count);
66 $bytes = substr($bytes, $count);
67 return $output;
68 }
69 }
70
71 /**
72 * Calculates a base-64 encoded, URL-safe sha-256 hmac.
73 *
74 * @param mixed $data
75 * Scalar value to be validated with the hmac.
76 * @param mixed $key
77 * A secret key, this can be any scalar value.
78 *
79 * @return string
80 * A base-64 encoded sha-256 hmac, with + replaced with -, / with _ and
81 * any = padding characters removed.
82 */
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.');
90 }
91
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);
95 }
96
97 /**
98 * Calculates a base-64 encoded, URL-safe sha-256 hash.
99 *
100 * @param string $data
101 * String to be hashed.
102 *
103 * @return string
104 * A base-64 encoded sha-256 hash, with + replaced with -, / with _ and
105 * any = padding characters removed.
106 */
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);
111 }
112
113 /**
114 * Compares strings in constant time.
115 *
116 * @param string $known_string
117 * The expected string.
118 * @param string $user_string
119 * The user supplied string to check.
120 *
121 * @return bool
122 * Returns TRUE when the two strings are equal, FALSE otherwise.
123 */
124 public static function hashEquals($known_string, $user_string) {
125 if (function_exists('hash_equals')) {
126 return hash_equals($known_string, $user_string);
127 }
128 else {
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);
133 return FALSE;
134 }
135
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);
138 return FALSE;
139 }
140
141 $known_len = strlen($known_string);
142 if ($known_len !== strlen($user_string)) {
143 return FALSE;
144 }
145
146 // This is security sensitive code. Do not optimize this for speed.
147 $result = 0;
148 for ($i = 0; $i < $known_len; $i++) {
149 $result |= (ord($known_string[$i]) ^ ord($user_string[$i]));
150 }
151
152 return $result === 0;
153 }
154 }
155
156 /**
157 * Returns a URL-safe, base64 encoded string of highly randomized bytes.
158 *
159 * @param $count
160 * The number of random bytes to fetch and base64 encode.
161 *
162 * @return string
163 * The base64 encoded result will have a length of up to 4 * $count.
164 *
165 * @see \Drupal\Component\Utility\Crypt::randomBytes()
166 */
167 public static function randomBytesBase64($count = 32) {
168 return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode(static::randomBytes($count)));
169 }
170
171 }