hash_pbkdf2()

hash_pbkdf2() — Generate a PBKDF2 key derivation of a supplied password.

Built-in function of PHP 8.5. The manual lists it as available in PHP 5 >= 5.5.0, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

Signature

hash_pbkdf2(string $algo, string $password, string $salt, int $iterations, int $length = 0, bool $binary = false, array $options = []): string

Parameters

ParameterTypeWhat it takes
$algostringName of selected hashing algorithm (e.g. "sha256"). For a list of supported algorithms see hash_hmac_algos(). Note: Non-cryptographic hash functions are not allowed.
$passwordstringThe password to use for the derivation.
$saltstringThe salt to use for the derivation. This value should be generated randomly.
$iterationsintThe number of internal iterations to perform for the derivation.
$lengthintThe 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).
$binaryboolWhen set to true, outputs raw binary data. false outputs lowercase hexits.
$optionsarrayAn array of options for the various hashing algorithms. Currently, only the "seed" key is supported by the MurmurHash variants.

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.

Example

A runnable snippet:

$password = "password"; $iterations = 600000; // Generate a cryptographically secure random salt using random_bytes() $salt = random_bytes(16); $hash = hash_pbkdf2("sha256", $password, $salt, $iterations, 20); var_dump($hash); // for raw binary, the $length needs to be halved for equivalent results $hash = hash_pbkdf2("sha256", $password, $salt, $iterations, 10, true); var_dump(bin2hex($hash));

Output:

string(20) "120fb6cffcf8b32c43e7" string(20) "120fb6cffcf8b32c43e7"

Changelog

VersionChange
8.0.0Now throws a ValueError exception on error. Previously, false was returned and an E_WARNING message was emitted.
7.2.0Usage of non-cryptographic hash functions (adler32, crc32, crc32b, fnv132, fnv1a32, fnv164, fnv1a64, joaat) was disabled.

See also

password_hash(), hash_hkdf()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page hash_pbkdf2() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.