Security.php 25.8 KB
Newer Older
1 2
<?php
/**
3 4 5
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
6 7 8
 */

namespace yii\base;
9

10 11 12 13 14 15 16 17
use yii\helpers\StringHelper;
use Yii;

/**
 * Security provides a set of methods to handle common security-related tasks.
 *
 * In particular, Security supports the following features:
 *
18 19
 * - Encryption/decryption: [[encryptByKey()]], [[decryptByKey()]], [[encryptByPassword()]] and [[decryptByPassword()]]
 * - Key derivation using standard algorithms: [[pbkdf2()]] and [[hkdf()]]
20 21 22
 * - Data tampering prevention: [[hashData()]] and [[validateData()]]
 * - Password validation: [[generatePasswordHash()]] and [[validatePassword()]]
 *
Qiang Xue committed
23
 * > Note: this class requires 'mcrypt' PHP extension. For the highest security level PHP version >= 5.5.0 is recommended.
24
 *
25 26 27 28 29 30 31
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Tom Worster <fsb@thefsb.org>
 * @author Klimov Paul <klimov.paul@gmail.com>
 * @since 2.0
 */
class Security extends Component
{
32
    /**
33
     * Cipher algorithm for mcrypt module.
34 35 36 37 38 39
     * AES has 128-bit block size and three key sizes: 128, 192 and 256 bits.
     * mcrypt offers the Rijndael cipher with block sizes of 128, 192 and 256
     * bits but only the 128-bit Rijndael is standardized in AES.
     * So to use AES in mycrypt, specify `'rijndael-128'` cipher and mcrypt
     * chooses the appropriate AES based on the length of the supplied key.
     */
40
    const MCRYPT_CIPHER = 'rijndael-128';
41 42 43
    /**
     * Block cipher operation mode for mcrypt module.
     */
44
    const MCRYPT_MODE = 'cbc';
45
    /**
46
     * Size in bytes of encryption key, message authentication key and KDF salt.
47
     */
48
    const KEY_SIZE = 16;
49 50 51
    /**
     * Hash algorithm for key derivation.
     */
52
    const KDF_HASH = 'sha256';
53
    /**
54
     * Hash algorithm for message authentication.
55
     */
56
    const MAC_HASH = 'sha256';
57
    /**
58
     * HKDF info value for derivation of message authentication key.
59
     */
60 61
    const AUTH_KEY_INFO = 'AuthorizationKey';

Carsten Brandt committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75
    /**
     * @var integer derivation iterations count.
     * Set as high as possible to hinder dictionary password attacks.
     */
    public $derivationIterations = 100000;
    /**
     * @var string strategy, which should be used to generate password hash.
     * Available strategies:
     * - 'password_hash' - use of PHP `password_hash()` function with PASSWORD_DEFAULT algorithm.
     *   This option is recommended, but it requires PHP version >= 5.5.0
     * - 'crypt' - use PHP `crypt()` function.
     */
    public $passwordHashStrategy = 'crypt';

76 77
    private $_cryptModule;

Carsten Brandt committed
78

79
    /**
80 81 82 83 84 85 86 87 88 89 90 91 92 93
     * Encrypts data using a password.
     * Derives keys for encryption and authentication from the password using PBKDF2 and a random salt,
     * which is deliberately slow to protect against dictionary attacks. Use [[encryptByKey()]] to
     * encrypt fast using a cryptographic key rather than a password. Key derivation time is
     * determined by [[$derivationIterations]], which should be set as high as possible.
     * The encrypted data includes a keyed message authentication code (MAC) so there is no need
     * to hash input or output data.
     * > Note: Avoid encrypting with passwords wherever possible. Nothing can protect against
     * poor-quality or compromosed passwords.
     * @param string $data the data to encrypt
     * @param string $password the password to use for encryption
     * @return string the encrypted data
     * @see decryptByPassword()
     * @see encryptByKey()
94
     */
95 96 97 98 99
    public function encryptByPassword($data, $password)
    {
        return $this->encrypt($data, true, $password, null);
    }

100
    /**
101 102 103 104 105 106 107 108 109 110 111 112
     * Encrypts data using a cyptograhic key.
     * Derives keys for encryption and authentication from the input key using HKDF and a random salt,
     * which is very fast relative to [[encryptByPassword()]]. The input key must be properly
     * random -- use [[generateRandomKey()]] to generate keys.
     * The encrypted data includes a keyed message authentication code (MAC) so there is no need
     * to hash input or output data.
     * @param string $data the data to encrypt
     * @param string $inputKey the input to use for encryption and authentication
     * @param string $info optional context and application specific information, see [[hkdf()]]
     * @return string the encrypted data
     * @see decryptByPassword()
     * @see encryptByKey()
113
     */
114 115 116 117 118
    public function encryptByKey($data, $inputKey, $info = null)
    {
        return $this->encrypt($data, false, $inputKey, $info);
    }

119
    /**
120 121 122 123 124
     * Verifies and decrypts data encrypted with [[encryptByPassword()]].
     * @param string $data the encrypted data to decrypt
     * @param string $password the password to use for decryption
     * @return bool|string the decrypted data or false on authentication failure
     * @see encryptByPassword()
125
     */
126 127 128 129 130
    public function decryptByPassword($data, $password)
    {
        return $this->decrypt($data, true, $password, null);
    }

131
    /**
132 133 134 135 136 137
     * Verifies and decrypts data encrypted with [[encryptByPassword()]].
     * @param string $data the encrypted data to decrypt
     * @param string $inputKey the input to use for encryption and authentication
     * @param string $info optional context and application specific information, see [[hkdf()]]
     * @return bool|string the decrypted data or false on authentication failure
     * @see encryptByKey()
138
     */
139 140 141 142 143
    public function decryptByKey($data, $inputKey, $info = null)
    {
        return $this->decrypt($data, false, $inputKey, $info);
    }

144
    /**
145 146 147 148
     * Initializes the mcrypt module.
     * @return resource the mcrypt module handle.
     * @throws InvalidConfigException if mcrypt extension is not installed
     * @throws Exception if mcrypt initialization fails
149
     */
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    protected function getCryptModule()
    {
        if ($this->_cryptModule === null) {
            if (!extension_loaded('mcrypt')) {
                throw new InvalidConfigException('The mcrypt PHP extension is not installed.');
            }

            $this->_cryptModule = @mcrypt_module_open(self::MCRYPT_CIPHER, '', self::MCRYPT_MODE, '');
            if ($this->_cryptModule === false) {
                $this->_cryptModule = null;
                throw new Exception('Failed to initialize the mcrypt module.');
            }
        }

        return $this->_cryptModule;
    }

    public function __destruct()
    {
        if ($this->_cryptModule !== null) {
            mcrypt_module_close($this->_cryptModule);
            $this->_cryptModule = null;
        }
    }
Qiang Xue committed
174

175 176 177

    /**
     * Encrypts data.
178 179 180 181
     * @param string $data data to be encrypted
     * @param bool $passwordBased set true to use password-based key derivation
     * @param string $secret the encryption password or key
     * @param string $info context/application specific information, e.g. a user ID
Carsten Brandt committed
182
     * See [RFC 5869 Section 3.2](https://tools.ietf.org/html/rfc5869#section-3.2) for more details.
183 184 185 186
     * @return string the encrypted data
     * @throws Exception if PHP Mcrypt extension is not loaded or failed to be initialized
     * @see decrypt()
     */
187
    protected function encrypt($data, $passwordBased, $secret, $info)
188
    {
189 190 191 192 193 194 195 196 197
        $module = $this->getCryptModule();

        $keySalt = $this->generateRandomKey(self::KEY_SIZE);
        if ($passwordBased) {
            $key = $this->pbkdf2(self::KDF_HASH, $secret, $keySalt, $this->derivationIterations, self::KEY_SIZE);
        } else {
            $key = $this->hkdf(self::KDF_HASH, $secret, $keySalt, $info, self::KEY_SIZE);
        }

198
        $data = $this->addPadding($data);
199 200
        $ivSize = mcrypt_enc_get_iv_size($module);
        $iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
201
        mcrypt_generic_init($module, $key, $iv);
202
        $encrypted = mcrypt_generic($module, $data);
203 204
        mcrypt_generic_deinit($module);

205 206 207 208 209 210 211 212 213 214
        $authKey = $this->hkdf(self::KDF_HASH, $key, null, self::AUTH_KEY_INFO, self::KEY_SIZE);
        $hashed = $this->hashData($iv . $encrypted, $authKey);

        /*
         * Output: [keySalt][MAC][IV][ciphertext]
         * - keySalt is KEY_SIZE bytes long
         * - MAC: message authentication code, length same as the output of MAC_HASH
         * - IV: initialization vector, length set by CRYPT_CIPHER and CRYPT_MODE, mcrypt_enc_get_iv_size()
         */
        return $keySalt . $hashed;
215 216 217
    }

    /**
218 219 220 221 222 223
     * Decrypts data.
     * @param string $data encrypted data to be decrypted.
     * @param bool $passwordBased set true to use password-based key derivation
     * @param string $secret the decryption password or key
     * @param string $info context/application specific information, @see encrypt()
     * @return bool|string the decrypted data or false on authentication failure
224 225
     * @see encrypt()
     */
226
    protected function decrypt($data, $passwordBased, $secret, $info)
227
    {
228 229 230 231 232
        $keySalt = StringHelper::byteSubstr($data, 0, self::KEY_SIZE);
        if ($passwordBased) {
            $key = $this->pbkdf2(self::KDF_HASH, $secret, $keySalt, $this->derivationIterations, self::KEY_SIZE);
        } else {
            $key = $this->hkdf(self::KDF_HASH, $secret, $keySalt, $info, self::KEY_SIZE);
233
        }
234 235 236 237 238 239 240 241

        $authKey = $this->hkdf(self::KDF_HASH, $key, null, self::AUTH_KEY_INFO, self::KEY_SIZE);
        $data = $this->validateData(StringHelper::byteSubstr($data, self::KEY_SIZE, null), $authKey);
        if ($data === false) {
            return false;
        }

        $module = $this->getCryptModule();
242 243
        $ivSize = mcrypt_enc_get_iv_size($module);
        $iv = StringHelper::byteSubstr($data, 0, $ivSize);
244
        $encrypted = StringHelper::byteSubstr($data, $ivSize, null);
245
        mcrypt_generic_init($module, $key, $iv);
246
        $decrypted = mdecrypt_generic($module, $encrypted);
247 248 249 250 251 252 253 254 255 256 257 258
        mcrypt_generic_deinit($module);

        return $this->stripPadding($decrypted);
    }

    /**
     * Adds a padding to the given data (PKCS #7).
     * @param string $data the data to pad
     * @return string the padded data
     */
    protected function addPadding($data)
    {
259 260 261
        $module = $this->getCryptModule();
        $blockSize = mcrypt_enc_get_block_size($module);
        $pad = $blockSize - (StringHelper::byteLength($data) % $blockSize);
262 263 264 265 266 267 268 269 270 271 272 273 274 275

        return $data . str_repeat(chr($pad), $pad);
    }

    /**
     * Strips the padding from the given data.
     * @param string $data the data to trim
     * @return string the trimmed data
     */
    protected function stripPadding($data)
    {
        $end = StringHelper::byteSubstr($data, -1, null);
        $last = ord($end);
        $n = StringHelper::byteLength($data) - $last;
276
        if (StringHelper::byteSubstr($data, $n, null) === str_repeat($end, $last)) {
277 278 279 280 281 282 283
            return StringHelper::byteSubstr($data, 0, $n);
        }

        return false;
    }

    /**
284 285 286 287 288
     * Derives a key from the given input key using the standard HKDF algorithm.
     * Implements HKDF spcified in [RFC 5869](https://tools.ietf.org/html/rfc5869).
     * Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.
     * @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
     * @param string $inputKey the source key
289
     * @param string $salt the random salt
290 291 292 293 294 295
     * @param string $info optional info to bind the derived key material to application-
     * and context-specific information, e.g. a user ID or API version, see
     * [RFC 5869](https://tools.ietf.org/html/rfc5869)
     * @param int $length length of the output key in bytes. If 0, the output key is
     * the length of the hash algorithm output.
     * @throws InvalidParamException
296 297
     * @return string the derived key
     */
Qiang Xue committed
298
    public function hkdf($algo, $inputKey, $salt = null, $info = null, $length = 0)
299
    {
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
        $test = @hash_hmac($algo, '', '', true);
        if (!$test) {
            throw new InvalidParamException('Failed to generate HMAC with hash algorithm: ' . $algo);
        }
        $hashLength = StringHelper::byteLength($test);
        if (is_string($length) && preg_match('{^\d{1,16}$}', $length)) {
            $length = (int) $length;
        }
        if (!is_integer($length) || $length < 0 || $length > 255 * $hashLength) {
            throw new InvalidParamException('Invalid length');
        }
        $blocks = $length !== 0 ? ceil($length / $hashLength) : 1;

        if ($salt === null) {
            $salt = str_repeat("\0", $hashLength);
        }
        $prKey = hash_hmac($algo, $inputKey, $salt, true);

        $hmac = '';
        $outputKey = '';
        for ($i = 1; $i <= $blocks; $i++) {
            $hmac = hash_hmac($algo, $hmac . $info . chr($i), $prKey, true);
            $outputKey .= $hmac;
323
        }
324 325 326 327 328

        if ($length !== 0) {
            $outputKey = StringHelper::byteSubstr($outputKey, 0, $length);
        }
        return $outputKey;
329 330 331
    }

    /**
332 333 334 335
     * Derives a key from the given password using the standard PBKDF2 algorithm.
     * Implements HKDF2 specified in [RFC 2898](http://tools.ietf.org/html/rfc2898#section-5.2)
     * Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.
     * @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
336 337
     * @param string $password the source password
     * @param string $salt the random salt
338 339 340 341 342
     * @param int $iterations the number of iterations of the hash algorithm. Set as high as
     * possible to hinder dictionary password attacks.
     * @param int $length length of the output key in bytes. If 0, the output key is
     * the length of the hash algorithm output.
     * @throws InvalidParamException
343 344
     * @return string the derived key
     */
Qiang Xue committed
345
    public function pbkdf2($algo, $password, $salt, $iterations, $length = 0)
346 347
    {
        if (function_exists('hash_pbkdf2')) {
348 349 350 351 352
            $outputKey = hash_pbkdf2($algo, $password, $salt, $iterations, $length, true);
            if ($outputKey === false) {
                throw new InvalidParamException('Invalid parameters to hash_pbkdf2()');
            }
            return $outputKey;
353
        }
354

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
        // todo: is there a nice way to reduce the code repetition in hkdf() and pbkdf2()?
        $test = @hash_hmac($algo, '', '', true);
        if (!$test) {
            throw new InvalidParamException('Failed to generate HMAC with hash algorithm: ' . $algo);
        }
        if (is_string($iterations) && preg_match('{^\d{1,16}$}', $iterations)) {
            $iterations = (int) $iterations;
        }
        if (!is_integer($iterations) || $iterations < 1) {
            throw new InvalidParamException('Invalid iterations');
        }
        if (is_string($length) && preg_match('{^\d{1,16}$}', $length)) {
            $length = (int) $length;
        }
        if (!is_integer($length) || $length < 0) {
            throw new InvalidParamException('Invalid length');
371
        }
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
        $hashLength = StringHelper::byteLength($test);
        $blocks = $length !== 0 ? ceil($length / $hashLength) : 1;

        $outputKey = '';
        for ($j = 1; $j <= $blocks; $j++) {
            $hmac = hash_hmac($algo, $salt . pack('N', $j), $password, true);
            $xorsum = $hmac;
            for ($i = 1; $i < $iterations; $i++) {
                $hmac = hash_hmac($algo, $hmac, $password, true);
                $xorsum ^= $hmac;
            }
            $outputKey .= $xorsum;
        }

        if ($length !== 0) {
            $outputKey = StringHelper::byteSubstr($outputKey, 0, $length);
        }
        return $outputKey;
390 391 392 393
    }

    /**
     * Prefixes data with a keyed hash value so that it can later be detected if it is tampered.
394 395
     * There is no need to hash inputs or outputs of [[encryptByKey()]] or [[encryptByPassword()]]
     * as those methods perform the task.
396
     * @param string $data the data to be protected
397 398
     * @param string $key the secret key to be used for generating hash. Should be a secure
     * cryptographic key.
399 400
     * @param boolean $rawHash whether the generated hash value is in raw binary format. If false, lowercase
     * hex digits will be generated.
401
     * @throws InvalidConfigException
402 403
     * @return string the data prefixed with the keyed hash
     * @see validateData()
404 405 406
     * @see generateRandomKey()
     * @see hkdf()
     * @see pbkdf2()
407
     */
408
    public function hashData($data, $key, $rawHash = false)
409
    {
410
        $hash = hash_hmac(self::MAC_HASH, $data, $key, $rawHash);
411 412 413 414
        if (!$hash) {
            throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . self::MAC_HASH);
        }
        return $hash . $data;
415 416 417 418 419 420 421 422 423
    }

    /**
     * Validates if the given data is tampered.
     * @param string $data the data to be validated. The data must be previously
     * generated by [[hashData()]].
     * @param string $key the secret key that was previously used to generate the hash for the data in [[hashData()]].
     * function to see the supported hashing algorithms on your system. This must be the same
     * as the value passed to [[hashData()]] when generating the hash for the data.
424 425 426 427
     * @param boolean $rawHash this should take the same value as when you generate the data using [[hashData()]].
     * It indicates whether the hash value in the data is in binary format. If false, it means the hash value consists
     * of lowercase hex digits only.
     * hex digits will be generated.
428
     * @throws InvalidConfigException
429 430 431
     * @return string the real data with the hash stripped off. False if the data is tampered.
     * @see hashData()
     */
432
    public function validateData($data, $key, $rawHash = false)
433
    {
434
        $test = @hash_hmac(self::MAC_HASH, '', '', $rawHash);
435 436 437 438 439 440 441
        if (!$test) {
            throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . self::MAC_HASH);
        }
        $hashLength = StringHelper::byteLength($test);
        if (StringHelper::byteLength($data) >= $hashLength) {
            $hash = StringHelper::byteSubstr($data, 0, $hashLength);
            $pureData = StringHelper::byteSubstr($data, $hashLength, null);
442

443
            $calculatedHash = hash_hmac(self::MAC_HASH, $pureData, $key, $rawHash);
444

445 446
            if ($this->compareString($hash, $calculatedHash)) {
                return $pureData;
447 448
            }
        }
tom-- committed
449
        return false;
450 451 452
    }

    /**
453 454
     * Generates specified number of random bytes.
     * Note that output may not be ASCII.
Vincent committed
455
     * @see generateRandomString() if you need a string.
456 457
     *
     * @param integer $length the number of bytes to generate
458
     * @throws Exception on failure.
459
     * @return string the generated random bytes
460
     */
461
    public function generateRandomKey($length = 32)
462
    {
463 464 465
        if (!extension_loaded('mcrypt')) {
            throw new InvalidConfigException('The mcrypt PHP extension is not installed.');
        }
466 467 468
        $bytes = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
        if ($bytes === false) {
            throw new Exception('Unable to generate random bytes.');
469
        }
470 471 472 473 474
        return $bytes;
    }

    /**
     * Generates a random string of specified length.
475
     * The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
476 477 478 479 480
     *
     * @param integer $length the length of the key in characters
     * @throws Exception Exception on failure.
     * @return string the generated random key
     */
481
    public function generateRandomString($length = 32)
482
    {
483 484 485 486
        $bytes = $this->generateRandomKey($length);
        // '=' character(s) returned by base64_encode() are always discarded because
        // they are guaranteed to be after position $length in the base64_encode() output.
        return strtr(substr(base64_encode($bytes), 0, $length), '+/', '_-');
487 488 489 490 491
    }

    /**
     * Generates a secure hash from a password and a random salt.
     *
492
     * The generated hash can be stored in database.
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
     * Later when a password needs to be validated, the hash can be fetched and passed
     * to [[validatePassword()]]. For example,
     *
     * ~~~
     * // generates the hash (usually done during user registration or when the password is changed)
     * $hash = Yii::$app->getSecurity()->generatePasswordHash($password);
     * // ...save $hash in database...
     *
     * // during login, validate if the password entered is correct using $hash fetched from database
     * if (Yii::$app->getSecurity()->validatePassword($password, $hash) {
     *     // password is good
     * } else {
     *     // password is bad
     * }
     * ~~~
     *
     * @param string $password The password to be hashed.
     * @param integer $cost Cost parameter used by the Blowfish hash algorithm.
     * The higher the value of cost,
     * the longer it takes to generate the hash and to verify a password against it. Higher cost
     * therefore slows down a brute-force attack. For best protection against brute for attacks,
     * set it to the highest value that is tolerable on production servers. The time taken to
515
     * compute the hash doubles for every increment by one of $cost.
516
     * @throws Exception on bad password parameter or cost parameter
517 518
     * @throws InvalidConfigException
     * @return string The password hash string. When [[passwordHashStrategy]] is set to 'crypt',
519
     * the output is always 60 ASCII characters, when set to 'password_hash' the output length
520
     * might increase in future versions of PHP (http://php.net/manual/en/function.password-hash.php)
521 522 523 524
     * @see validatePassword()
     */
    public function generatePasswordHash($password, $cost = 13)
    {
525 526 527 528 529
        switch ($this->passwordHashStrategy) {
            case 'password_hash':
                if (!function_exists('password_hash')) {
                    throw new InvalidConfigException('Password hash key strategy "password_hash" requires PHP >= 5.5.0, either upgrade your environment or use another strategy.');
                }
530
                /** @noinspection PhpUndefinedConstantInspection */
531 532 533 534
                return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]);
            case 'crypt':
                $salt = $this->generateSalt($cost);
                $hash = crypt($password, $salt);
535 536
                // strlen() is safe since crypt() returns only ascii
                if (!is_string($hash) || strlen($hash) !== 60) {
537 538 539 540 541
                    throw new Exception('Unknown error occurred while generating hash.');
                }
                return $hash;
            default:
                throw new InvalidConfigException("Unknown password hash strategy '{$this->passwordHashStrategy}'");
542 543 544 545 546 547 548 549 550
        }
    }

    /**
     * Verifies a password against a hash.
     * @param string $password The password to verify.
     * @param string $hash The hash to verify the password against.
     * @return boolean whether the password is correct.
     * @throws InvalidParamException on bad password or hash parameters or if crypt() with Blowfish hash is not available.
551
     * @throws InvalidConfigException on unsupported password hash strategy is configured.
552 553 554 555 556 557 558 559 560 561 562 563
     * @see generatePasswordHash()
     */
    public function validatePassword($password, $hash)
    {
        if (!is_string($password) || $password === '') {
            throw new InvalidParamException('Password must be a string and cannot be empty.');
        }

        if (!preg_match('/^\$2[axy]\$(\d\d)\$[\.\/0-9A-Za-z]{22}/', $hash, $matches) || $matches[1] < 4 || $matches[1] > 30) {
            throw new InvalidParamException('Hash is invalid.');
        }

564 565 566 567 568 569 570 571 572
        switch ($this->passwordHashStrategy) {
            case 'password_hash':
                if (!function_exists('password_verify')) {
                    throw new InvalidConfigException('Password hash key strategy "password_hash" requires PHP >= 5.5.0, either upgrade your environment or use another strategy.');
                }
                return password_verify($password, $hash);
            case 'crypt':
                $test = crypt($password, $hash);
                $n = strlen($test);
573
                if ($n !== 60) {
574 575 576 577 578
                    return false;
                }
                return $this->compareString($test, $hash);
            default:
                throw new InvalidConfigException("Unknown password hash strategy '{$this->passwordHashStrategy}'");
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
        }
    }

    /**
     * Generates a salt that can be used to generate a password hash.
     *
     * The PHP [crypt()](http://php.net/manual/en/function.crypt.php) built-in function
     * requires, for the Blowfish hash algorithm, a salt string in a specific format:
     * "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters
     * from the alphabet "./0-9A-Za-z".
     *
     * @param integer $cost the cost parameter
     * @return string the random salt value.
     * @throws InvalidParamException if the cost parameter is not between 4 and 31
     */
    protected function generateSalt($cost = 13)
    {
Qiang Xue committed
596
        $cost = (int)$cost;
597 598 599 600
        if ($cost < 4 || $cost > 31) {
            throw new InvalidParamException('Cost must be between 4 and 31.');
        }

601 602 603
        // Get a 20-byte random string
        $rand = $this->generateRandomKey(20);
        // Form the prefix that specifies Blowfish (bcrypt) algorithm and cost parameter.
604 605 606 607 608 609
        $salt = sprintf("$2y$%02d$", $cost);
        // Append the random salt data in the required base64 format.
        $salt .= str_replace('+', '.', substr(base64_encode($rand), 0, 22));

        return $salt;
    }
610 611 612 613 614

    /**
     * Performs string comparison using timing attack resistant approach.
     * @see http://codereview.stackexchange.com/questions/13512
     * @param string $expected string to compare.
615
     * @param string $actual user-supplied string.
616 617
     * @return boolean whether strings are equal.
     */
618
    public function compareString($expected, $actual)
619
    {
620 621 622 623 624 625 626
        $expected .= "\0";
        $actual .= "\0";
        $expectedLength = StringHelper::byteLength($expected);
        $actualLength = StringHelper::byteLength($actual);
        $diff = $expectedLength - $actualLength;
        for ($i = 0; $i < $actualLength; $i++) {
            $diff |= (ord($actual[$i]) ^ ord($expected[$i % $expectedLength]));
627 628 629
        }
        return $diff === 0;
    }
Qiang Xue committed
630
}