Hướng dẫn how to verify hash password in php - cách xác minh mật khẩu băm trong php

(Php 5> = 5.5.0, Php 7, Php 8)

password_verify - xác minh rằng mật khẩu khớp với bămVerifies that a password matches a hash

Sự mô tả

password_verify (chuỗi $password, chuỗi $hash): bool(string $password, string $hash): bool

Lưu ý rằng password_hash () trả về thuật toán, chi phí và muối như một phần của băm đã trả lại. Do đó, tất cả thông tin cần thiết để xác minh hàm băm được bao gồm trong đó. Điều này cho phép chức năng xác minh xác minh băm mà không cần lưu trữ riêng cho thông tin muối hoặc thuật toán.password_hash() returns the algorithm, cost and salt as part of the returned hash. Therefore, all information that's needed to verify the hash is included in it. This allows the verify function to verify the hash without needing separate storage for the salt or algorithm information.

Chức năng này là an toàn trước các cuộc tấn công thời gian.

Thông số

password

Mật khẩu của người dùng.

hash

Một hàm băm được tạo bởi password_hash ().password_hash().

Trả về giá trị

Trả về true nếu mật khẩu và băm phù hợp, hoặc false nếu không.true if the password and hash match, or false otherwise.

Ví dụ

Ví dụ #1 password_verify () Ví dụpassword_verify() example

// See the password_hash() example to see where this came from.
$hash '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (

password_verify('rasmuslerdorf'$hash)) {
    echo 
'Password is valid!';
} else {
    echo 
'Invalid password.';
}
?>

Ví dụ trên sẽ xuất ra:

Xem thêm

  • password_hash () - Tạo mật khẩu băm
  • »& Nbsp; triển khai userland
  • natri_crypto_pwhash_str_verify () - xác minh rằng mật khẩu khớp với băm

Mật khẩu lớp mã đầy đủ:

Class Password {

    public function __construct() {}


    /**
     * Hash the password using the specified algorithm
     *
     * @param string $password The password to hash
     * @param int    $algo     The algorithm to use (Defined by PASSWORD_* constants)
     * @param array  $options  The options for the algorithm to use
     *
     * @return string|false The hashed password, or false on error.
     */
    function password_hash($password, $algo, array $options = array()) {
        if (!function_exists('crypt')) {
            trigger_error("Crypt must be loaded for password_hash to function", E_USER_WARNING);
            return null;
        }
        if (!is_string($password)) {
            trigger_error("password_hash(): Password must be a string", E_USER_WARNING);
            return null;
        }
        if (!is_int($algo)) {
            trigger_error("password_hash() expects parameter 2 to be long, " . gettype($algo) . " given", E_USER_WARNING);
            return null;
        }
        switch ($algo) {
            case PASSWORD_BCRYPT :
                // Note that this is a C constant, but not exposed to PHP, so we don't define it here.
                $cost = 10;
                if (isset($options['cost'])) {
                    $cost = $options['cost'];
                    if ($cost < 4 || $cost > 31) {
                        trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING);
                        return null;
                    }
                }
                // The length of salt to generate
                $raw_salt_len = 16;
                // The length required in the final serialization
                $required_salt_len = 22;
                $hash_format = sprintf("$2y$%02d$", $cost);
                break;
            default :
                trigger_error(sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo), E_USER_WARNING);
                return null;
        }
        if (isset($options['salt'])) {
            switch (gettype($options['salt'])) {
                case 'NULL' :
                case 'boolean' :
                case 'integer' :
                case 'double' :
                case 'string' :
                    $salt = (string)$options['salt'];
                    break;
                case 'object' :
                    if (method_exists($options['salt'], '__tostring')) {
                        $salt = (string)$options['salt'];
                        break;
                    }
                case 'array' :
                case 'resource' :
                default :
                    trigger_error('password_hash(): Non-string salt parameter supplied', E_USER_WARNING);
                    return null;
            }
            if (strlen($salt) < $required_salt_len) {
                trigger_error(sprintf("password_hash(): Provided salt is too short: %d expecting %d", strlen($salt), $required_salt_len), E_USER_WARNING);
                return null;
            } elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) {
                $salt = str_replace('+', '.', base64_encode($salt));
            }
        } else {
            $salt = str_replace('+', '.', base64_encode($this->generate_entropy($required_salt_len)));
        }
        $salt = substr($salt, 0, $required_salt_len);

        $hash = $hash_format . $salt;

        $ret = crypt($password, $hash);

        if (!is_string($ret) || strlen($ret) <= 13) {
            return false;
        }

        return $ret;
    }


    /**
     * Generates Entropy using the safest available method, falling back to less preferred methods depending on support
     *
     * @param int $bytes
     *
     * @return string Returns raw bytes
     */
    function generate_entropy($bytes){
        $buffer = '';
        $buffer_valid = false;
        if (function_exists('mcrypt_create_iv') && !defined('PHALANGER')) {
            $buffer = mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM);
            if ($buffer) {
                $buffer_valid = true;
            }
        }
        if (!$buffer_valid && function_exists('openssl_random_pseudo_bytes')) {
            $buffer = openssl_random_pseudo_bytes($bytes);
            if ($buffer) {
                $buffer_valid = true;
            }
        }
        if (!$buffer_valid && is_readable('/dev/urandom')) {
            $f = fopen('/dev/urandom', 'r');
            $read = strlen($buffer);
            while ($read < $bytes) {
                $buffer .= fread($f, $bytes - $read);
                $read = strlen($buffer);
            }
            fclose($f);
            if ($read >= $bytes) {
                $buffer_valid = true;
            }
        }
        if (!$buffer_valid || strlen($buffer) < $bytes) {
            $bl = strlen($buffer);
            for ($i = 0; $i < $bytes; $i++) {
                if ($i < $bl) {
                    $buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255));
                } else {
                    $buffer .= chr(mt_rand(0, 255));
                }
            }
        }
        return $buffer;
    }

    /**
     * Get information about the password hash. Returns an array of the information
     * that was used to generate the password hash.
     *
     * array(
     *    'algo' => 1,
     *    'algoName' => 'bcrypt',
     *    'options' => array(
     *        'cost' => 10,
     *    ),
     * )
     *
     * @param string $hash The password hash to extract info from
     *
     * @return array The array of information about the hash.
     */
    function password_get_info($hash) {
        $return = array('algo' => 0, 'algoName' => 'unknown', 'options' => array(), );
        if (substr($hash, 0, 4) == '$2y$' && strlen($hash) == 60) {
            $return['algo'] = PASSWORD_BCRYPT;
            $return['algoName'] = 'bcrypt';
            list($cost) = sscanf($hash, "$2y$%d$");
            $return['options']['cost'] = $cost;
        }
        return $return;
    }

    /**
     * Determine if the password hash needs to be rehashed according to the options provided
     *
     * If the answer is true, after validating the password using password_verify, rehash it.
     *
     * @param string $hash    The hash to test
     * @param int    $algo    The algorithm used for new password hashes
     * @param array  $options The options array passed to password_hash
     *
     * @return boolean True if the password needs to be rehashed.
     */
    function password_needs_rehash($hash, $algo, array $options = array()) {
        $info = password_get_info($hash);
        if ($info['algo'] != $algo) {
            return true;
        }
        switch ($algo) {
            case PASSWORD_BCRYPT :
                $cost = isset($options['cost']) ? $options['cost'] : 10;
                if ($cost != $info['options']['cost']) {
                    return true;
                }
                break;
        }
        return false;
    }

    /**
     * Verify a password against a hash using a timing attack resistant approach
     *
     * @param string $password The password to verify
     * @param string $hash     The hash to verify against
     *
     * @return boolean If the password matches the hash
     */
    public function password_verify($password, $hash) {
        if (!function_exists('crypt')) {
            trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING);
            return false;
        }
        $ret = crypt($password, $hash);
        if (!is_string($ret) || strlen($ret) != strlen($hash) || strlen($ret) <= 13) {
            return false;
        }

        $status = 0;
        for ($i = 0; $i < strlen($ret); $i++) {
            $status |= (ord($ret[$i]) ^ ord($hash[$i]));
        }

        return $status === 0;
    }

}

Làm thế nào để bạn xác minh rằng mật khẩu khớp với băm của nó?

Hàm password_verify () có thể xác minh rằng hàm băm đã phù hợp với mật khẩu đã cho. Lưu ý rằng hàm password_hash () có thể trả về thuật toán, chi phí và muối như một phần của hàm băm đã trả lại. Do đó, tất cả thông tin cần xác minh hàm băm bao gồm trong đó. can verify that given hash matches the given password. Note that the password_hash() function can return the algorithm, cost, and salt as part of a returned hash. Therefore, all information that needs to verify a hash that includes in it.

Mật khẩu băm trong PHP là gì?

password_hash () tạo một hàm băm mật khẩu mới bằng thuật toán băm một chiều mạnh mẽ.Các thuật toán sau đây hiện đang được hỗ trợ: password_default - Sử dụng thuật toán BCRYPT (mặc định là Php 5.5. 0).Lưu ý rằng hằng số này được thiết kế để thay đổi theo thời gian vì các thuật toán mới và mạnh hơn được thêm vào PHP.. The following algorithms are currently supported: PASSWORD_DEFAULT - Use the bcrypt algorithm (default as of PHP 5.5. 0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP.

Làm thế nào để password_verify hoạt động trong PHP?

Hàm password_verify () được sử dụng để khớp với mật khẩu băm với mật khẩu gốc.Một hàm khác, password_hash () được sử dụng để tạo giá trị băm dựa trên thuật toán băm, chi phí và giá trị muối.Hàm password_verify () chứa tất cả thông tin băm để xác minh băm bằng mật khẩu.used to match the hash password with the original password. Another function, password_hash() is used to generate the hash value based on the hashing algorithm, cost, and salt value. The password_verify() function contains all hashing information to verify the hash with the password.

Chức năng nào tốt nhất để sử dụng trong PHP để băm mật khẩu?

Chủ yếu, các nhà phát triển PHP nên sử dụng hàm password_hash () để tạo mật khẩu băm.Tương tự, bạn nên sử dụng hàm password_verify () để xác minh băm của bất kỳ mật khẩu nào bạn tạo.password_hash() function to generate hashed passwords. Similarly, you should use the password_verify() function to verify the hashes of any passwords you create.