PasswordHelper.php 1.02 KB
<?php

namespace App\Helpers;

use Illuminate\Support\Str;

class PasswordHelper
{
    /**
     * 密码Hash生成
     * @param string $password
     * @return string
     */
    public static function make(string $password): string
    {
        $header     = "pbkdf2_sha256";
        $iterations = 260000;
        $salt       = Str::random(22);
        $hash       = base64_encode(hash_pbkdf2("SHA256", $password, $salt, $iterations, 0, true));
        return implode('$', [$header, $iterations, $salt, $hash]);
    }


    /**
     * 密码Hash验证
     * @param string $password
     * @param string $hash
     * @return bool
     */
    public static function verify(string $password, string $hash): bool
    {
        if (empty($hash) || !Str::contains($hash, '$')) {
            return false;
        }

        [$header, $iterations, $salt, $hash] = explode("$", $hash);
        $verifyHash = base64_encode(hash_pbkdf2("SHA256", $password, $salt, (int)$iterations, 0, true));
        return hash_equals($hash, $verifyHash);
    }
}