[PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1]
hash_hmac — Generate a keyed hash value using the HMAC method
Description
hash_hmac[
string $algo
,
string $data
,
string
$key
,
bool $binary
= false
]: string
Parameters
algo
Name of selected hashing algorithm [i.e. "md5", "sha256", "haval160,4", etc..] See hash_hmac_algos[] for a list of supported algorithms.
data
Message to be hashed.
key
Shared secret key used for generating the HMAC variant of the message digest.
binary
When set to true
, outputs raw binary data. false
outputs lowercase hexits.
Return Values
Returns a string containing the calculated message digest as lowercase hexits unless
binary
is set to true in which case the raw binary representation of the message digest is returned.
Changelog
8.0.0 | hash_hmac[] now throws a ValueError exception if algo is unknown or is a non-cryptographic hash function; previously, false was returned instead.
|
7.2.0 | Usage of non-cryptographic hash functions [adler32, crc32, crc32b, fnv132, fnv1a32, fnv164, fnv1a64, joaat] was disabled. |
Examples
Example #1 hash_hmac[] example
The above example will output:
b8e7ae12510bdfb1812e463a7f086122cf37e4f7
See Also
- hash[] - Generate a hash value [message digest]
- hash_hmac_algos[] - Return a list of registered hashing algorithms suitable for hash_hmac
- hash_init[] - Initialize an incremental hashing context
- hash_hmac_file[] - Generate a keyed hash value using the HMAC method and the contents of a given file
Korbendallas ¶
4 years ago
Very important notice, if you pass array to $data, php will generate a Warning, return a NULL and continue your application. Which I think is critical vulnerability as this function used to check authorisation typically.
Example:
Of course not documented feature.
Michiel Thalen, Thalent ¶
5 years ago
As Michael uggests we should take care not to compare the hash using == [or ===]. Since PHP version 5.6 we can now use hash_equals[].
So the example will be:
Michael ¶
9 years ago
Please be careful when comparing hashes. In certain cases, information can be leaked by using a timing attack. It takes advantage of the == operator only comparing until it finds a difference in the two strings. To prevent it, you have two options.
Option 1: hash both hashed strings first - this doesn't stop the timing difference, but it makes the information useless.
Option 2: always compare the whole string.
KC Cloyd ¶
12 years ago
Sometimes a hosting provider doesn't provide access to the Hash extension. Here is a clone of the hash_hmac function you can use in the event you need an HMAC generator and Hash is not available. It's only usable with MD5 and SHA1 encryption algorithms, but its output is identical to the official hash_hmac function [so far at least].
Example Use:
pete dot walker at NOSPAM dot me dot com ¶
9 years ago
A function implementing the algorithm outlined in RFC 6238 [//tools.ietf.org/html/rfc6238]