PHP.mk документација

password_needs_rehash

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.password-needs-rehash.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.password-needs-rehash.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
password_needs_rehash

Референца за `function.password-needs-rehash.php` со подобрена типографија и навигација.

function.password-needs-rehash.php

password_needs_rehash

Распакување на вгнездени низи

password_needs_rehashChecks if the given hash matches the given options

= NULL

password_needs_rehash(string $hash, string|int|null $algo, array $options = []): bool

This function checks to see if the supplied hash implements the algorithm and options provided. If not, it is assumed that the hash needs to be rehashed.

Параметри

hash

Хеш создаден од password_hash().

algo

А , што ќе одговара на што го означува алгоритамот што треба да се користи при хеширање на лозинката.

options

Асоцијативен низ што содржи опции. Погледнете ги константите за алгоритми за лозинки за документација за поддржаните опции за секој алгоритам.

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true if the hash should be rehashed to match the given algo and options, или false otherwise.

Дневник на промени

Верзија = NULL
7.4.0 На algo параметарот сега е nullable. string параметарот очекува intсега, но сепак прифаќа

Примери

Пример #1 Употреба на password_needs_rehash()

<?php

$password
= 'rasmuslerdorf';
$hash = '$2y$12$4Umg0rCJwMswRw/l.SwHvuQV01coP0eWmGzd61QH2RvAOMANUBGC.';

$algorithm = PASSWORD_BCRYPT;
// bcrypt's cost parameter can change over time as hardware improves
$options = ['cost' => 13];

// Verify stored hash against plain-text password
if (password_verify($password, $hash)) {
// Check if either the algorithm or the options have changed
if (password_needs_rehash($hash, $algorithm, $options)) {
// If so, create a new hash, and replace the old one
$newHash = password_hash($password, $algorithm, $options);

// Update the user record with the $newHash
}

// Perform the login.
}
?>

Белешки од корисници 3 белешки

php dot net at muer dot nl
пред 11 години
This function cannot check if a string is a MD5 or SHA1 hash. It can only tell you if a password, hashed using the password_hash function, needs to be put through the hashing function again to keep up to date with the new defaults.

The only time you can use this function is when your user logs in and you have already checked by means of password_verify that the password entered is actually correct. At that point, if password_needs_rehash returns true, you can put the plain text password through the password_hash function.
admin на torntech dot com
пред 11 години
Some other use-cases for the password_needs_rehash function is when you have specified using the PASSWORD_DEFAULT algorithm for password_hash.
As mentioned on the Password Hashing Predefined Constants and password_hash pages, the algorithm used by PASSWORD_DEFAULT is subject to change as different versions of PHP are released.
Additionally password_needs_rehash would be used if you have changed the optional cost or static salt (DO NOT USE A STATIC SALT) requirements of your password_hash options.

Full example:

<?php

$new = [
    'options' => ['cost' => 11],
    'algo' => PASSWORD_DEFAULT,
    'hash' => null
];

$password = 'rasmuslerdorf';

//stored hash of password
$oldHash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

//verify stored hash against plain-text password
if (true === password_verify($password, $oldHash)) {
    //verify legacy password to new password_hash options
    if (true === password_needs_rehash($oldHash, $new['algo'], $new['options'])) {
        //rehash/store plain-text password using new hash
        $newHash = password_hash($password, $new['algo'], $new['options']);
        echo $newHash;
    }
}
?>

The above example will output something similar to:
$2y$11$Wu5rN3u38.g/XWdUeA6Wj.PD.F0fLXXmZrMNFyzzg2UxkVmxlk41W
geekasylum at google mail
пред 7 години
This function can indeed be used to assist in transparently updating legacy passwords (those not using the password_hash() function - eg: perhaps something using MD5 or SHA1)

In legacy sites, when authenticating a user (during login) first check the password using password_verify(). If that fails it may simply be because the user's password hash was created long ago by a legacy or home-brew password algorithm.

You can then re-check the password against the site's legacy password algorithm.  If that fails too, then the login fails, since the supplied password did not authenticate against either the new, or the old password tests.

If any one of those two test was successfull, you know that the password is good so you would then call password_needs_rehash() on the stored hash, and it will properly indicate if the password hash needs to be re-computed, either because it's an unrecognised (legacy) hash or it's a modern hash created by password_hash(), which may just need its cost index updated.

Simply store the recomputed hash in the database and you now have a password_verify() compatible password for that user and the second test can be skipped in future logins (but still check if it needs rehashing).
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.