yii\base\Security::pbkdf2 PHP Méthode

pbkdf2() public méthode

Implements HKDF2 specified in RFC 2898 Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.
public pbkdf2 ( string $algo, string $password, string $salt, integer $iterations, integer $length ) : string
$algo string a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
$password string the source password
$salt string the random salt
$iterations integer the number of iterations of the hash algorithm. Set as high as possible to hinder dictionary password attacks.
$length integer length of the output key in bytes. If 0, the output key is the length of the hash algorithm output.
Résultat string the derived key
    public function pbkdf2($algo, $password, $salt, $iterations, $length = 0)
    {
        if (function_exists('hash_pbkdf2')) {
            $outputKey = hash_pbkdf2($algo, $password, $salt, $iterations, $length, true);
            if ($outputKey === false) {
                throw new InvalidParamException('Invalid parameters to hash_pbkdf2()');
            }
            return $outputKey;
        }
        // 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_int($iterations) || $iterations < 1) {
            throw new InvalidParamException('Invalid iterations');
        }
        if (is_string($length) && preg_match('{^\\d{1,16}$}', $length)) {
            $length = (int) $length;
        }
        if (!is_int($length) || $length < 0) {
            throw new InvalidParamException('Invalid length');
        }
        $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;
    }

Usage Example

Exemple #1
0
 /**
  * @inheritdoc
  */
 public function pbkdf2($algo, $password, $salt, $iterations, $length = 0)
 {
     return parent::pbkdf2($algo, $password, $salt, $iterations, $length);
 }