PHP - Hash pbkdf2() 函式



定義和用法

hash_pbkdf2() 函式返回給定密碼的 PBKDF2 金鑰派生。

PBKDF2 代表基於密碼的金鑰派生函式 2。PBKDF2 金鑰派生函式使用偽隨機函式,例如基於雜湊的訊息認證碼 (HMAC),它應用於給定的密碼或訊息以及鹽值,並且該過程會迭代多次以獲得金鑰。它主要用於雜湊密碼,PBKDF2 金鑰派生函式的設計使得攻擊者難以猜測被雜湊的原始密碼。

語法

hash_pbkdf2 ( string $algo , string $password , string $salt , int $iterations [
   , int $length = 0 [, bool $raw_output = FALSE ]
] ) : string

引數

序號 引數及描述
1

algo

雜湊演算法的名稱。hash 提供了大量的演算法,一些重要的演算法包括 md5、sha256 等。

要獲取支援的完整演算法列表,請檢視 hash_algos()

2

password

需要為其生成 PBKDF2 金鑰派生的密碼。

3

salt

要用於派生 PBKDF2 金鑰派生的鹽值。

4

iterations

為獲得最終派生而執行的內部迭代次數。

5

length

最終 PBKDF2 金鑰派生的長度。如果 raw_output 為 TRUE,則派生的金鑰對應於位元組長度;如果 raw_output 為 FALSE,則其將是派生金鑰位元組長度的兩倍。

6

raw_output

如果 raw_output 為 false,則輸出將是一個包含小寫十六進位制數的字串;如果為 TRUE,則輸出將是原始二進位制資料。

返回值

hash_pbkdf2() 返回一個字串,如果 raw_output 為 false,則該字串包含派生金鑰作為小寫十六進位制數;如果 raw_output 設定為 TRUE,則該字串將是派生金鑰的原始二進位制表示。

PHP 版本

此函式適用於 PHP 5.5.0 以上版本。

示例 1

使用 hash_pbkdf2() -

<?php
   $password = "mypassword";
   $iterations = 500;
   $salt = 'testingkey';
   $pbkdf2_hash = hash_pbkdf2("md5", $password, $salt, $iterations, 25);
   echo $pbkdf2_hash;	
?>

輸出

這將產生以下結果:

cb0130970bb39f6a95d193934

示例 2

使用 1000 次迭代的 hash_pbkdf2() -

<?php
   $password = "mypassword";
   $iterations = 1000;
   $salt = openssl_random_pseudo_bytes(10); //generates pseudo-random string of bytes
   $pbkdf2_hash = hash_pbkdf2("sha256", $password, $salt, $iterations, 10);
   echo $pbkdf2_hash;
?>

輸出

這將產生以下結果:

0c31d20aa2

示例 3

使用 raw_output 為 true 的 hash_pbkdf2() -

<?php
   $password = "mypassword";
   $iterations = 1000;
   $salt = openssl_random_pseudo_bytes(10); //generates pseudo-random string of bytes
   $pbkdf2_hash = hash_pbkdf2("sha256", $password, $salt, $iterations, 10, true);
   echo $pbkdf2_hash;
?>

示例 4

使用 raw_output 為 true 的 hash_pbkdf2() -

在本例中,我們將使用 base64_encode() PHP 函式,該函式將 hash_pbkdf2() 的原始二進位制輸出轉換為可讀字串。

<?php
   echo base64_encode(
      hash_pbkdf2("sha256", 'passwordtest', openssl_random_pseudo_bytes(10), 5000, 10, true)
   );
?>

輸出

這將產生以下結果:

2FogGKtZxmt4iQ==
php_function_reference.htm
廣告