PHP - password_needs_rehash() 函式



PHP 雜湊password_needs_rehash()函式用於確定給定雜湊是否與給定選項匹配,並檢查雜湊是否需要重新雜湊。在 PHP 中,“雜湊”是指由雜湊演算法生成的固定大小的字元字串。輸入資料可以是任何大小,演算法會根據該輸入生成唯一的輸出。

選項通常包括使用的演算法和各種引數,例如成本,這些引數會影響雜湊過程的安全性與效能。

如果雜湊可以重新雜湊以匹配給定的演算法和選項,則此函式返回布林值“true”;否則,它返回“false”。

語法

以下是 PHP 雜湊 password_needs_rehash() 函式的語法:

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

引數

此函式接受以下引數:

  • hash - 由 password_hash() 函式建立的雜湊。
  • algo - 密碼演算法常量,表示雜湊密碼時要使用的演算法。
  • options - 包含選項的關聯陣列。

返回值

如果應重新雜湊雜湊以匹配給定的 algo 和 options,則此函式返回 true,否則返回 false。

示例 1

以下程式演示了 PHP 雜湊password_needs_rehash()函式的用法:

<?php
   $passw = "53nh46u74m3nt3";
   $hashp = '$argon2i$v=19$m=65536,t=4,p=1$dmJMWlhFUEFvaTFSeFhFNQ$Cpgdj1rHw21Y7WqnMpUAFFp7uLubGoU7Zxc09Pn8t9k';
   $algo = PASSWORD_ARGON2I;
   $options = ['cost' => 12];
   $conf = password_needs_rehash($hashp, $algo);
   echo "The given password: $passw";
   echo "\nThe given password hash: $hashp";
   echo "\nThe given algo: $algo";
   $result = password_needs_rehash($hashp, $algo, $options);
   if($result){
	   $newhas = password_hash($passw, $algo);
	   echo "\nThe function result: ";
	   var_dump($result);
	   echo "Hash need to rehashed, Suggested for the new hash: \n";
	   echo $newhas;
	   }
   else {
	   echo "\nThe function result: ";
	   var_dump($result);
	   echo "Matched, no need to be rehashed: ";
   }
?>

輸出

上述程式產生以下輸出:

The given password: 53nh46u74m3nt3
The given password hash: $argon2i$v=19$m=65536,t=4,p=1$dmJMWlhFUEFvaTFSeFhFNQ$Cpgdj1rHw21Y7WqnMpUAFFp7uLubGoU7Zxc09Pn8t9k
The given algo: argon2i
The function result: bool(false)
Matched, no need to be rehashed:

示例 2

如果給定的雜湊與給定的選項不匹配,則此函式返回“true”。

以下是 PHP 雜湊password_needs_rehash()函式的另一個示例。我們使用此函式來檢查給定的雜湊是否與給定的選項匹配:

<?php
   $passw = "53nh46u74m3nt3";
   $hashp = '$argon2i$v=19$m=1024,t=2,p=2$d1JJWnNHMkVEekZwcTFUdA$zeSi7c/Adh/1KCTHddoF39Xxwo9ystxRzHEnRa0lQeM';
   $algo = PASSWORD_ARGON2I;
   $options = ['cost' => 12];
   $conf = password_needs_rehash($hashp, $algo);
   echo "The given password: $passw";
   echo "\nThe given password hash: $hashp";
   echo "\nThe given algo: $algo";
   $result = password_needs_rehash($hashp, $algo, $options);
   if($result){
	   $newhas = password_hash($passw, $algo);
	   echo "\nThe function result: ";
	   var_dump($result);
	   echo "Hash need to rehashed, suggested for the new hash: \n";
	   echo $newhas;
	   }
   else {
	   echo "\nThe function result: ";
	   var_dump($result);
	  echo "\nMatched, no need to be rehashed: ";
   }
?>

輸出

執行上述程式後,將顯示以下輸出:

The given password: 53nh46u74m3nt3
The given password hash: $argon2i$v=19$m=1024,t=2,p=2$d1JJWnNHMkVEekZwcTFUdA$zeSi7c/Adh/1KCTHddoF39Xxwo9ystxRzHEnRa0lQeM
The given algo: argon2i
The function result: bool(true)
Hash need to rehashed, suggested for the new hash:
$argon2i$v=19$m=65536,t=4,p=1$amw3ZHM3bEpYN3lWYlp6eg$wNWs5nkT2/Yx7NXkOJ4TZ4EqUmc58Xhb6N3IX5shNc8
php_function_reference.htm
廣告