PHP Function Reference

PHP hash_pbkdf2() Function



The PHP hash_pbkdf2() function is used to generate a PBKDF2 key derivation of a supplied password.

The PBKDF2 stands for Password-Based Key Derivation Function 2. The PBKDF2 key derivation function applies a pseudorandom function, such as hash-based message authentication code (HMAC), to the input password or message along with a salt value and repeats the process many times to produce a derived key. It is mainly used to hash password and the PBKDF2 key derivation function is designed in such a way that it becomes difficult for the attacker to guess the original password hashed.

Syntax

hash_pbkdf2(algo, password, salt, 
            iterations, length, binary)

Parameters

algo Required. Specify the name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..). A list of supported algorithms can be found using hash_algos() function.
password Required. Specify the password to use for the derivation.
salt Required. Specify the salt to use for the derivation. This value should be generated randomly.
iterations Required. Specify the number of internal iterations to perform for the derivation.
length Optional. Specify the length of the output string. If binary is true this corresponds to the byte-length of the derived key, if binary is false this corresponds to twice the byte-length of the derived key (as every byte of the key is returned as two hexits). If 0 is passed, the entire output of the supplied algorithm is used.
binary Optional. If set to true, outputs raw binary data. Default is false which outputs lowercase hexits.

Return Value

Returns a string containing the derived key as lowercase hexits unless binary is set to true in which case the raw binary representation of the derived key is returned.

Exceptions

Raises E_WARNING if the algorithm is unknown, the iterations parameter is less than or equal to 0, the length is less than 0 or the salt is too long (greater than INT_MAX - 4).

Example: hash_pbkdf2() example

In the example below, a pair of separate keys is produced, suitable for creation of an encrypt-then-HMAC construct, using AES-256 and SHA-256 for encryption and authentication respectively.

<?php
$password = "myPassword";
$iterations = 100;

//generating a random IV using 
//openssl_random_pseudo_bytes()
//random_bytes() or another 
//suitable source of randomness
$salt = openssl_random_pseudo_bytes(16);

//using hash_pbkdf2 function
$hash = hash_pbkdf2("md5", $password, $salt, 
                    $iterations, 20);
var_dump($hash);

//for raw binary, the $length needs to 
//be halved for equivalent results
$hash = hash_pbkdf2("md5", $password, $salt, 
                    $iterations, 10, true);
var_dump(bin2hex($hash));
?>

The output of the above code will be:

string(20) "14f6762e90e52a1e05bc"
string(20) "14f6762e90e52a1e05bc"

❮ PHP Hash Reference