Completed
Push — better-test-security ( 2aeb47 )
by Carsten
06:53
created

Security::pbkdf2()   C

Complexity

Conditions 16
Paths 57

Size

Total Lines 46
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 177.1886
Metric Value
dl 0
loc 46
rs 5.0026
ccs 5
cts 35
cp 0.1429
cc 16
eloc 30
nc 57
nop 5
crap 177.1886

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\base;
9
10
use yii\helpers\StringHelper;
11
use Yii;
12
13
/**
14
 * Security provides a set of methods to handle common security-related tasks.
15
 *
16
 * In particular, Security supports the following features:
17
 *
18
 * - Encryption/decryption: [[encryptByKey()]], [[decryptByKey()]], [[encryptByPassword()]] and [[decryptByPassword()]]
19
 * - Key derivation using standard algorithms: [[pbkdf2()]] and [[hkdf()]]
20
 * - Data tampering prevention: [[hashData()]] and [[validateData()]]
21
 * - Password validation: [[generatePasswordHash()]] and [[validatePassword()]]
22
 *
23
 * > Note: this class requires 'OpenSSL' PHP extension for random key/string generation on Windows and
24
 * for encryption/decryption on all platforms. For the highest security level PHP version >= 5.5.0 is recommended.
25
 *
26
 * @author Qiang Xue <[email protected]>
27
 * @author Tom Worster <[email protected]>
28
 * @author Klimov Paul <[email protected]>
29
 * @since 2.0
30
 */
31
class Security extends Component
32
{
33
    /**
34
     * @var string The cipher to use for encryption and decryption.
35
     */
36
    public $cipher = 'AES-128-CBC';
37
    /**
38
     * @var array[] Look-up table of block sizes and key sizes for each supported OpenSSL cipher.
39
     *
40
     * In each element, the key is one of the ciphers supported by OpenSSL (@see openssl_get_cipher_methods()).
41
     * The value is an array of two integers, the first is the cipher's block size in bytes and the second is
42
     * the key size in bytes.
43
     *
44
     * > Warning: All OpenSSL ciphers that we recommend are in the default value, i.e. AES in CBC mode.
45
     *
46
     * > Note: Yii's encryption protocol uses the same size for cipher key, HMAC signature key and key
47
     * derivation salt.
48
     */
49
    public $allowedCiphers = [
50
        'AES-128-CBC' => [16, 16],
51
        'AES-192-CBC' => [16, 24],
52
        'AES-256-CBC' => [16, 32],
53
    ];
54
    /**
55
     * @var string Hash algorithm for key derivation. Recommend sha256, sha384 or sha512.
56
     * @see hash_algos()
57
     */
58
    public $kdfHash = 'sha256';
59
    /**
60
     * @var string Hash algorithm for message authentication. Recommend sha256, sha384 or sha512.
61
     * @see hash_algos()
62
     */
63
    public $macHash = 'sha256';
64
    /**
65
     * @var string HKDF info value for derivation of message authentication key.
66
     * @see hkdf()
67
     */
68
    public $authKeyInfo = 'AuthorizationKey';
69
    /**
70
     * @var integer derivation iterations count.
71
     * Set as high as possible to hinder dictionary password attacks.
72
     */
73
    public $derivationIterations = 100000;
74
    /**
75
     * @var string strategy, which should be used to generate password hash.
76
     * Available strategies:
77
     * - 'password_hash' - use of PHP `password_hash()` function with PASSWORD_DEFAULT algorithm.
78
     *   This option is recommended, but it requires PHP version >= 5.5.0
79
     * - 'crypt' - use PHP `crypt()` function.
80
     * @deprecated Since version 2.0.7, [[generatePasswordHash()]] ignores [[passwordHashStrategy]] and
81
     * uses `password_hash()` when available or `crypt()` when not.
82
     */
83
    public $passwordHashStrategy;
84
    /**
85
     * @var integer Default cost used for password hashing.
86
     * Allowed value is between 4 and 31.
87
     * @see generatePasswordHash()
88
     * @since 2.0.6
89
     */
90
    public $passwordHashCost = 13;
91
92
93
    /**
94
     * Encrypts data using a password.
95
     * Derives keys for encryption and authentication from the password using PBKDF2 and a random salt,
96
     * which is deliberately slow to protect against dictionary attacks. Use [[encryptByKey()]] to
97
     * encrypt fast using a cryptographic key rather than a password. Key derivation time is
98
     * determined by [[$derivationIterations]], which should be set as high as possible.
99
     * The encrypted data includes a keyed message authentication code (MAC) so there is no need
100
     * to hash input or output data.
101
     * > Note: Avoid encrypting with passwords wherever possible. Nothing can protect against
102
     * poor-quality or compromised passwords.
103
     * @param string $data the data to encrypt
104
     * @param string $password the password to use for encryption
105
     * @return string the encrypted data
106
     * @see decryptByPassword()
107
     * @see encryptByKey()
108
     */
109 1
    public function encryptByPassword($data, $password)
110
    {
111 1
        return $this->encrypt($data, true, $password, null);
112
    }
113
114
    /**
115
     * Encrypts data using a cryptographic key.
116
     * Derives keys for encryption and authentication from the input key using HKDF and a random salt,
117
     * which is very fast relative to [[encryptByPassword()]]. The input key must be properly
118
     * random -- use [[generateRandomKey()]] to generate keys.
119
     * The encrypted data includes a keyed message authentication code (MAC) so there is no need
120
     * to hash input or output data.
121
     * @param string $data the data to encrypt
122
     * @param string $inputKey the input to use for encryption and authentication
123
     * @param string $info optional context and application specific information, see [[hkdf()]]
124
     * @return string the encrypted data
125
     * @see decryptByKey()
126
     * @see encryptByPassword()
127
     */
128 1
    public function encryptByKey($data, $inputKey, $info = null)
129
    {
130 1
        return $this->encrypt($data, false, $inputKey, $info);
131
    }
132
133
    /**
134
     * Verifies and decrypts data encrypted with [[encryptByPassword()]].
135
     * @param string $data the encrypted data to decrypt
136
     * @param string $password the password to use for decryption
137
     * @return boolean|string the decrypted data or false on authentication failure
138
     * @see encryptByPassword()
139
     */
140 10
    public function decryptByPassword($data, $password)
141
    {
142 10
        return $this->decrypt($data, true, $password, null);
143
    }
144
145
    /**
146
     * Verifies and decrypts data encrypted with [[encryptByPassword()]].
147
     * @param string $data the encrypted data to decrypt
148
     * @param string $inputKey the input to use for encryption and authentication
149
     * @param string $info optional context and application specific information, see [[hkdf()]]
150
     * @return boolean|string the decrypted data or false on authentication failure
151
     * @see encryptByKey()
152
     */
153 10
    public function decryptByKey($data, $inputKey, $info = null)
154
    {
155 10
        return $this->decrypt($data, false, $inputKey, $info);
156
    }
157
158
    /**
159
     * Encrypts data.
160
     *
161
     * @param string $data data to be encrypted
162
     * @param boolean $passwordBased set true to use password-based key derivation
163
     * @param string $secret the encryption password or key
164
     * @param string $info context/application specific information, e.g. a user ID
165
     * See [RFC 5869 Section 3.2](https://tools.ietf.org/html/rfc5869#section-3.2) for more details.
166
     *
167
     * @return string the encrypted data
168
     * @throws InvalidConfigException on OpenSSL not loaded
169
     * @throws Exception on OpenSSL error
170
     * @see decrypt()
171
     */
172 2
    protected function encrypt($data, $passwordBased, $secret, $info)
173
    {
174 2
        if (!extension_loaded('openssl')) {
175
            throw new InvalidConfigException('Encryption requires the OpenSSL PHP extension');
176
        }
177 2
        if (!isset($this->allowedCiphers[$this->cipher][0], $this->allowedCiphers[$this->cipher][1])) {
178
            throw new InvalidConfigException($this->cipher . ' is not an allowed cipher');
179
        }
180
181 2
        list($blockSize, $keySize) = $this->allowedCiphers[$this->cipher];
182
183 2
        $keySalt = $this->generateRandomKey($keySize);
184 2
        if ($passwordBased) {
185 1
            $key = $this->pbkdf2($this->kdfHash, $secret, $keySalt, $this->derivationIterations, $keySize);
186 1
        } else {
187 1
            $key = $this->hkdf($this->kdfHash, $secret, $keySalt, $info, $keySize);
188
        }
189
190 2
        $iv = $this->generateRandomKey($blockSize);
191
192 2
        $encrypted = openssl_encrypt($data, $this->cipher, $key, OPENSSL_RAW_DATA, $iv);
193 2
        if ($encrypted === false) {
194
            throw new \yii\base\Exception('OpenSSL failure on encryption: ' . openssl_error_string());
195
        }
196
197 2
        $authKey = $this->hkdf($this->kdfHash, $key, null, $this->authKeyInfo, $keySize);
198 2
        $hashed = $this->hashData($iv . $encrypted, $authKey);
199
200
        /*
201
         * Output: [keySalt][MAC][IV][ciphertext]
202
         * - keySalt is KEY_SIZE bytes long
203
         * - MAC: message authentication code, length same as the output of MAC_HASH
204
         * - IV: initialization vector, length $blockSize
205
         */
206 2
        return $keySalt . $hashed;
207
    }
208
209
    /**
210
     * Decrypts data.
211
     *
212
     * @param string $data encrypted data to be decrypted.
213
     * @param boolean $passwordBased set true to use password-based key derivation
214
     * @param string $secret the decryption password or key
215
     * @param string $info context/application specific information, @see encrypt()
216
     *
217
     * @return boolean|string the decrypted data or false on authentication failure
218
     * @throws InvalidConfigException on OpenSSL not loaded
219
     * @throws Exception on OpenSSL error
220
     * @see encrypt()
221
     */
222 20
    protected function decrypt($data, $passwordBased, $secret, $info)
223
    {
224 20
        if (!extension_loaded('openssl')) {
225
            throw new InvalidConfigException('Encryption requires the OpenSSL PHP extension');
226
        }
227 20
        if (!isset($this->allowedCiphers[$this->cipher][0], $this->allowedCiphers[$this->cipher][1])) {
228
            throw new InvalidConfigException($this->cipher . ' is not an allowed cipher');
229
        }
230
231 20
        list($blockSize, $keySize) = $this->allowedCiphers[$this->cipher];
232
233 20
        $keySalt = StringHelper::byteSubstr($data, 0, $keySize);
234 20
        if ($passwordBased) {
235 10
            $key = $this->pbkdf2($this->kdfHash, $secret, $keySalt, $this->derivationIterations, $keySize);
236 10
        } else {
237 10
            $key = $this->hkdf($this->kdfHash, $secret, $keySalt, $info, $keySize);
238
        }
239
240 20
        $authKey = $this->hkdf($this->kdfHash, $key, null, $this->authKeyInfo, $keySize);
241 20
        $data = $this->validateData(StringHelper::byteSubstr($data, $keySize, null), $authKey);
242 20
        if ($data === false) {
243 2
            return false;
244
        }
245
246 20
        $iv = StringHelper::byteSubstr($data, 0, $blockSize);
247 20
        $encrypted = StringHelper::byteSubstr($data, $blockSize, null);
248
249 20
        $decrypted = openssl_decrypt($encrypted, $this->cipher, $key, OPENSSL_RAW_DATA, $iv);
250 20
        if ($decrypted === false) {
251
            throw new \yii\base\Exception('OpenSSL failure on decryption: ' . openssl_error_string());
252
        }
253
254 20
        return $decrypted;
255
    }
256
257
    /**
258
     * Derives a key from the given input key using the standard HKDF algorithm.
259
     * Implements HKDF specified in [RFC 5869](https://tools.ietf.org/html/rfc5869).
260
     * Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.
261
     * @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
262
     * @param string $inputKey the source key
263
     * @param string $salt the random salt
264
     * @param string $info optional info to bind the derived key material to application-
265
     * and context-specific information, e.g. a user ID or API version, see
266
     * [RFC 5869](https://tools.ietf.org/html/rfc5869)
267
     * @param integer $length length of the output key in bytes. If 0, the output key is
268
     * the length of the hash algorithm output.
269
     * @throws InvalidParamException when HMAC generation fails.
270
     * @return string the derived key
271
     */
272 27
    public function hkdf($algo, $inputKey, $salt = null, $info = null, $length = 0)
273
    {
274 27
        $test = @hash_hmac($algo, '', '', true);
275 27
        if (!$test) {
276
            throw new InvalidParamException('Failed to generate HMAC with hash algorithm: ' . $algo);
277
        }
278 27
        $hashLength = StringHelper::byteLength($test);
279 27
        if (is_string($length) && preg_match('{^\d{1,16}$}', $length)) {
280
            $length = (int) $length;
281
        }
282 27
        if (!is_int($length) || $length < 0 || $length > 255 * $hashLength) {
283
            throw new InvalidParamException('Invalid length');
284
        }
285 27
        $blocks = $length !== 0 ? ceil($length / $hashLength) : 1;
286
287 27
        if ($salt === null) {
288 20
            $salt = str_repeat("\0", $hashLength);
289 20
        }
290 27
        $prKey = hash_hmac($algo, $inputKey, $salt, true);
291
292 27
        $hmac = '';
293 27
        $outputKey = '';
294 27
        for ($i = 1; $i <= $blocks; $i++) {
295 27
            $hmac = hash_hmac($algo, $hmac . $info . chr($i), $prKey, true);
296 27
            $outputKey .= $hmac;
297 27
        }
298
299 27
        if ($length !== 0) {
300 27
            $outputKey = StringHelper::byteSubstr($outputKey, 0, $length);
301 27
        }
302 27
        return $outputKey;
303
    }
304
305
    /**
306
     * Derives a key from the given password using the standard PBKDF2 algorithm.
307
     * Implements HKDF2 specified in [RFC 2898](http://tools.ietf.org/html/rfc2898#section-5.2)
308
     * Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.
309
     * @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
310
     * @param string $password the source password
311
     * @param string $salt the random salt
312
     * @param integer $iterations the number of iterations of the hash algorithm. Set as high as
313
     * possible to hinder dictionary password attacks.
314
     * @param integer $length length of the output key in bytes. If 0, the output key is
315
     * the length of the hash algorithm output.
316
     * @return string the derived key
317
     * @throws InvalidParamException when hash generation fails due to invalid params given.
318
     */
319 19
    public function pbkdf2($algo, $password, $salt, $iterations, $length = 0)
320
    {
321 19
        if (function_exists('hash_pbkdf2')) {
322 19
            $outputKey = hash_pbkdf2($algo, $password, $salt, $iterations, $length, true);
323 19
            if ($outputKey === false) {
324
                throw new InvalidParamException('Invalid parameters to hash_pbkdf2()');
325
            }
326 19
            return $outputKey;
327
        }
328
329
        // todo: is there a nice way to reduce the code repetition in hkdf() and pbkdf2()?
330
        $test = @hash_hmac($algo, '', '', true);
331
        if (!$test) {
332
            throw new InvalidParamException('Failed to generate HMAC with hash algorithm: ' . $algo);
333
        }
334
        if (is_string($iterations) && preg_match('{^\d{1,16}$}', $iterations)) {
335
            $iterations = (int) $iterations;
336
        }
337
        if (!is_int($iterations) || $iterations < 1) {
338
            throw new InvalidParamException('Invalid iterations');
339
        }
340
        if (is_string($length) && preg_match('{^\d{1,16}$}', $length)) {
341
            $length = (int) $length;
342
        }
343
        if (!is_int($length) || $length < 0) {
344
            throw new InvalidParamException('Invalid length');
345
        }
346
        $hashLength = StringHelper::byteLength($test);
347
        $blocks = $length !== 0 ? ceil($length / $hashLength) : 1;
348
349
        $outputKey = '';
350
        for ($j = 1; $j <= $blocks; $j++) {
351
            $hmac = hash_hmac($algo, $salt . pack('N', $j), $password, true);
352
            $xorsum = $hmac;
353
            for ($i = 1; $i < $iterations; $i++) {
354
                $hmac = hash_hmac($algo, $hmac, $password, true);
355
                $xorsum ^= $hmac;
356
            }
357
            $outputKey .= $xorsum;
358
        }
359
360
        if ($length !== 0) {
361
            $outputKey = StringHelper::byteSubstr($outputKey, 0, $length);
362
        }
363
        return $outputKey;
364
    }
365
366
    /**
367
     * Prefixes data with a keyed hash value so that it can later be detected if it is tampered.
368
     * There is no need to hash inputs or outputs of [[encryptByKey()]] or [[encryptByPassword()]]
369
     * as those methods perform the task.
370
     * @param string $data the data to be protected
371
     * @param string $key the secret key to be used for generating hash. Should be a secure
372
     * cryptographic key.
373
     * @param boolean $rawHash whether the generated hash value is in raw binary format. If false, lowercase
374
     * hex digits will be generated.
375
     * @return string the data prefixed with the keyed hash
376
     * @throws InvalidConfigException when HMAC generation fails.
377
     * @see validateData()
378
     * @see generateRandomKey()
379
     * @see hkdf()
380
     * @see pbkdf2()
381
     */
382 3
    public function hashData($data, $key, $rawHash = false)
383
    {
384 3
        $hash = hash_hmac($this->macHash, $data, $key, $rawHash);
385 3
        if (!$hash) {
386
            throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . $this->macHash);
387
        }
388 3
        return $hash . $data;
389
    }
390
391
    /**
392
     * Validates if the given data is tampered.
393
     * @param string $data the data to be validated. The data must be previously
394
     * generated by [[hashData()]].
395
     * @param string $key the secret key that was previously used to generate the hash for the data in [[hashData()]].
396
     * function to see the supported hashing algorithms on your system. This must be the same
397
     * as the value passed to [[hashData()]] when generating the hash for the data.
398
     * @param boolean $rawHash this should take the same value as when you generate the data using [[hashData()]].
399
     * It indicates whether the hash value in the data is in binary format. If false, it means the hash value consists
400
     * of lowercase hex digits only.
401
     * hex digits will be generated.
402
     * @return string the real data with the hash stripped off. False if the data is tampered.
403
     * @throws InvalidConfigException when HMAC generation fails.
404
     * @see hashData()
405
     */
406 21
    public function validateData($data, $key, $rawHash = false)
407
    {
408 21
        $test = @hash_hmac($this->macHash, '', '', $rawHash);
409 21
        if (!$test) {
410
            throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . $this->macHash);
411
        }
412 21
        $hashLength = StringHelper::byteLength($test);
413 21
        if (StringHelper::byteLength($data) >= $hashLength) {
414 21
            $hash = StringHelper::byteSubstr($data, 0, $hashLength);
415 21
            $pureData = StringHelper::byteSubstr($data, $hashLength, null);
416
417 21
            $calculatedHash = hash_hmac($this->macHash, $pureData, $key, $rawHash);
418
419 21
            if ($this->compareString($hash, $calculatedHash)) {
420 21
                return $pureData;
421
            }
422 3
        }
423 3
        return false;
424
    }
425
426
    private $_useLibreSSL;
427
    private $_randomFile;
428
429
    /**
430
     * Generates specified number of random bytes.
431
     * Note that output may not be ASCII.
432
     * @see generateRandomString() if you need a string.
433
     *
434
     * @param integer $length the number of bytes to generate
435
     * @return string the generated random bytes
436
     * @throws InvalidParamException if wrong length is specified
437
     * @throws Exception on failure.
438
     */
439 34
    public function generateRandomKey($length = 32)
440
    {
441 34
        if (function_exists('random_bytes')) {
442
            return random_bytes($length);
443
        }
444
445 34
        if (!is_int($length)) {
446 3
            throw new InvalidParamException('First parameter ($length) must be an integer');
447
        }
448
449 31
        if ($length < 1) {
450 2
            throw new InvalidParamException('First parameter ($length) must be greater than 0');
451
        }
452
453
        // The recent LibreSSL RNGs are faster and likely better than /dev/urandom.
454
        // Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL.
455
        // https://bugs.php.net/bug.php?id=71143
456 29
        if ($this->_useLibreSSL === null) {
457 29
            $this->_useLibreSSL = defined('OPENSSL_VERSION_TEXT')
458 29
                && preg_match('{^LibreSSL (\d\d?)\.(\d\d?)\.(\d\d?)$}', OPENSSL_VERSION_TEXT, $matches)
459 29
                && (10000 * $matches[1]) + (100 * $matches[2]) + $matches[3] >= 20105;
460 29
        }
461
462
        // Since 5.4.0, openssl_random_pseudo_bytes() reads from CryptGenRandom on Windows instead
463
        // of using OpenSSL library. LibreSSL is OK everywhere but don't use OpenSSL on non-Windows.
464 29
        if ($this->_useLibreSSL
465
            || (
466 29
                DIRECTORY_SEPARATOR !== '/'
467 29
                && substr_compare(PHP_OS, 'win', 0, 3, true) === 0
468 29
                && function_exists('openssl_random_pseudo_bytes')
469
            )
470 29
        ) {
471
            $key = openssl_random_pseudo_bytes($length, $cryptoStrong);
472
            if ($cryptoStrong === false) {
473
                throw new Exception(
474
                    'openssl_random_pseudo_bytes() set $crypto_strong false. Your PHP setup is insecure.'
475
                );
476
            }
477
            if ($key !== false && StringHelper::byteLength($key) === $length) {
478
                return $key;
479
            }
480
        }
481
482
        // mcrypt_create_iv() does not use libmcrypt. Since PHP 5.3.7 it directly reads
483
        // CryptGenRandom on Windows. Elsewhere it directly reads /dev/urandom.
484 29
        if (function_exists('mcrypt_create_iv')) {
485 27
            $key = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
486 27
            if (StringHelper::byteLength($key) === $length) {
487 27
                return $key;
488
            }
489
        }
490
491
        // If not on Windows, try to open a random device.
492 2
        if ($this->_randomFile === null && DIRECTORY_SEPARATOR === '/') {
493
            // urandom is a symlink to random on FreeBSD.
494 2
            $device = PHP_OS === 'FreeBSD' ? '/dev/random' : '/dev/urandom';
495
            // Check random device for special character device protection mode. Use lstat()
496
            // instead of stat() in case an attacker arranges a symlink to a fake device.
497 2
            $lstat = @lstat($device);
498 2
            if ($lstat !== false && ($lstat['mode'] & 0170000) === 020000) {
499 2
                $this->_randomFile = fopen($device, 'rb') ?: null;
500
501 2
                if (is_resource($this->_randomFile)) {
502
                    // Reduce PHP stream buffer from default 8192 bytes to optimize data
503
                    // transfer from the random device for smaller values of $length.
504
                    // This also helps to keep future randoms out of user memory space.
505 2
                    $bufferSize = 8;
506
507 2
                    if (function_exists('stream_set_read_buffer')) {
508 2
                        stream_set_read_buffer($this->_randomFile, $bufferSize);
509 2
                    }
510
                    // stream_set_read_buffer() isn't implemented on HHVM
511 2
                    if (function_exists('stream_set_chunk_size')) {
512 2
                        stream_set_chunk_size($this->_randomFile, $bufferSize);
513 2
                    }
514 2
                }
515 2
            }
516 2
        }
517
518 2
        if (is_resource($this->_randomFile)) {
519 2
            $buffer = '';
520 2
            $stillNeed = $length;
521 2
            while ($stillNeed > 0) {
522 2
                $someBytes = fread($this->_randomFile, $stillNeed);
523 2
                if ($someBytes === false) {
524
                    break;
525
                }
526 2
                $buffer .= $someBytes;
527 2
                $stillNeed -= StringHelper::byteLength($buffer);
528 2
                if ($stillNeed === 0) {
529
                    // Leaving file pointer open in order to make next generation faster by reusing it.
530 2
                    return $buffer;
531
                }
532
            }
533
            fclose($this->_randomFile);
534
            $this->_randomFile = null;
535
        }
536
537
        throw new Exception('Unable to generate a random key');
538
    }
539
540
    /**
541
     * Generates a random string of specified length.
542
     * The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
543
     *
544
     * @param integer $length the length of the key in characters
545
     * @return string the generated random key
546
     * @throws Exception on failure.
547
     */
548 23
    public function generateRandomString($length = 32)
549
    {
550 23
        if (!is_int($length)) {
551
            throw new InvalidParamException('First parameter ($length) must be an integer');
552
        }
553
554 23
        if ($length < 1) {
555
            throw new InvalidParamException('First parameter ($length) must be greater than 0');
556
        }
557
558 23
        $bytes = $this->generateRandomKey($length);
559
        // '=' character(s) returned by base64_encode() are always discarded because
560
        // they are guaranteed to be after position $length in the base64_encode() output.
561 23
        return strtr(substr(base64_encode($bytes), 0, $length), '+/', '_-');
562
    }
563
564
    /**
565
     * Generates a secure hash from a password and a random salt.
566
     *
567
     * The generated hash can be stored in database.
568
     * Later when a password needs to be validated, the hash can be fetched and passed
569
     * to [[validatePassword()]]. For example,
570
     *
571
     * ```php
572
     * // generates the hash (usually done during user registration or when the password is changed)
573
     * $hash = Yii::$app->getSecurity()->generatePasswordHash($password);
574
     * // ...save $hash in database...
575
     *
576
     * // during login, validate if the password entered is correct using $hash fetched from database
577
     * if (Yii::$app->getSecurity()->validatePassword($password, $hash) {
578
     *     // password is good
579
     * } else {
580
     *     // password is bad
581
     * }
582
     * ```
583
     *
584
     * @param string $password The password to be hashed.
585
     * @param integer $cost Cost parameter used by the Blowfish hash algorithm.
586
     * The higher the value of cost,
587
     * the longer it takes to generate the hash and to verify a password against it. Higher cost
588
     * therefore slows down a brute-force attack. For best protection against brute-force attacks,
589
     * set it to the highest value that is tolerable on production servers. The time taken to
590
     * compute the hash doubles for every increment by one of $cost.
591
     * @return string The password hash string. When [[passwordHashStrategy]] is set to 'crypt',
592
     * the output is always 60 ASCII characters, when set to 'password_hash' the output length
593
     * might increase in future versions of PHP (http://php.net/manual/en/function.password-hash.php)
594
     * @throws Exception on bad password parameter or cost parameter.
595
     * @see validatePassword()
596
     */
597 1
    public function generatePasswordHash($password, $cost = null)
598
    {
599 1
        if ($cost === null) {
600 1
            $cost = $this->passwordHashCost;
601 1
        }
602
603 1
        if (function_exists('password_hash')) {
604
            /** @noinspection PhpUndefinedConstantInspection */
605 1
            return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]);
606
        }
607
608
        $salt = $this->generateSalt($cost);
609
        $hash = crypt($password, $salt);
610
        // strlen() is safe since crypt() returns only ascii
611
        if (!is_string($hash) || strlen($hash) !== 60) {
612
            throw new Exception('Unknown error occurred while generating hash.');
613
        }
614
615
        return $hash;
616
    }
617
618
    /**
619
     * Verifies a password against a hash.
620
     * @param string $password The password to verify.
621
     * @param string $hash The hash to verify the password against.
622
     * @return boolean whether the password is correct.
623
     * @throws InvalidParamException on bad password/hash parameters or if crypt() with Blowfish hash is not available.
624
     * @see generatePasswordHash()
625
     */
626 1
    public function validatePassword($password, $hash)
627
    {
628 1
        if (!is_string($password) || $password === '') {
629
            throw new InvalidParamException('Password must be a string and cannot be empty.');
630
        }
631
632 1
        if (!preg_match('/^\$2[axy]\$(\d\d)\$[\.\/0-9A-Za-z]{22}/', $hash, $matches)
633 1
            || $matches[1] < 4
634 1
            || $matches[1] > 30
635 1
        ) {
636
            throw new InvalidParamException('Hash is invalid.');
637
        }
638
639 1
        if (function_exists('password_verify')) {
640 1
            return password_verify($password, $hash);
641
        }
642
643
        $test = crypt($password, $hash);
644
        $n = strlen($test);
645
        if ($n !== 60) {
646
            return false;
647
        }
648
649
        return $this->compareString($test, $hash);
650
    }
651
652
    /**
653
     * Generates a salt that can be used to generate a password hash.
654
     *
655
     * The PHP [crypt()](http://php.net/manual/en/function.crypt.php) built-in function
656
     * requires, for the Blowfish hash algorithm, a salt string in a specific format:
657
     * "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters
658
     * from the alphabet "./0-9A-Za-z".
659
     *
660
     * @param integer $cost the cost parameter
661
     * @return string the random salt value.
662
     * @throws InvalidParamException if the cost parameter is out of the range of 4 to 31.
663
     */
664
    protected function generateSalt($cost = 13)
665
    {
666
        $cost = (int) $cost;
667
        if ($cost < 4 || $cost > 31) {
668
            throw new InvalidParamException('Cost must be between 4 and 31.');
669
        }
670
671
        // Get a 20-byte random string
672
        $rand = $this->generateRandomKey(20);
673
        // Form the prefix that specifies Blowfish (bcrypt) algorithm and cost parameter.
674
        $salt = sprintf("$2y$%02d$", $cost);
675
        // Append the random salt data in the required base64 format.
676
        $salt .= str_replace('+', '.', substr(base64_encode($rand), 0, 22));
677
678
        return $salt;
679
    }
680
681
    /**
682
     * Performs string comparison using timing attack resistant approach.
683
     * @see http://codereview.stackexchange.com/questions/13512
684
     * @param string $expected string to compare.
685
     * @param string $actual user-supplied string.
686
     * @return boolean whether strings are equal.
687
     */
688 41
    public function compareString($expected, $actual)
689
    {
690 41
        $expected .= "\0";
691 41
        $actual .= "\0";
692 41
        $expectedLength = StringHelper::byteLength($expected);
693 41
        $actualLength = StringHelper::byteLength($actual);
694 41
        $diff = $expectedLength - $actualLength;
695 41
        for ($i = 0; $i < $actualLength; $i++) {
696 41
            $diff |= (ord($actual[$i]) ^ ord($expected[$i % $expectedLength]));
697 41
        }
698 41
        return $diff === 0;
699
    }
700
}
701