PHP Function Reference

PHP hash_hkdf() Function



The PHP hash_hkdf() function is used to generate a keyed hash value using the HMAC method.

The HKDF is a simple key that is derived using HMAC algorithm like "md5", "sha256", a input key and a salt key.

HMAC stands for Hash-based Message Authentication Code. It makes use of cryptographic hash function like "md5", "sha256" and a secret key to return the message digest hash of the given data.

Syntax

hash_hkdf(algo, key, length, info, salt)

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.

Note: Non-cryptographic hash functions are not allowed.
key Required. Specify the input keying material (raw binary). It can not be empty.
length Optional. Specify the desired output length in bytes. It can not be greater than 255 times the chosen hash function size. If length is 0, the output length will default to the chosen hash function size.
info Optional. Specify application/context-specific info string.
salt Optional. Specify salt to use during derivation. Adding random salt significantly improves the strength of HKDF.

Return Value

Returns a string containing a raw binary representation of the derived key (also known as output keying material - OKM), or false on failure.

Exceptions

Raises E_WARNING if key is empty, algo is unknown/non-cryptographic, length is less than 0 or too large (greater than 255 times the size of the hash function).

Example: hash_hkdf() 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
//generating random key and salt 
//to strengthen it during derivation
$inputKey = random_bytes(32);
$salt = random_bytes(16);

//deriving a pair of separate 
//keys using the same input
$encryptionKey = hash_hkdf('sha256', $inputKey, 32, 
                       'aes-256-encryption', $salt);
$authenticationKey = hash_hkdf('sha256', $inputKey, 32, 
                       'sha-256-authentication', $salt);

var_dump($encryptionKey !== $authenticationKey);
?>

The output of the above code will be:

bool(true)

❮ PHP Hash Reference