PHP hash_hmac() Function

Definition
In PHP, hash_hmac() creates a keyed hash of your data. Only someone with the secret key can make the same value.
Use it to sign cookies, API requests and webhooks, and to check that a message was not changed.
Syntax
Call hash_hmac() with the values you need. Start with this line.
$mac = hash_hmac('sha256', $data, $secretKey);
| Call | What it does |
|---|
hash_hmac('sha256', 'msg', 'key') | Returns a 64-character hex signature. |
hash_hmac('sha256', 'msg', 'key', true) | Returns 32 raw bytes. |
Compare signatures with hash_equals(), never with ==.
Library declarations
hash_hmac(string $algo, string $data, string $key, bool $binary = false): string
Parameters
| Parameter | Description |
|---|
| algo | Required. A cryptographic algorithm such as "sha256". See hash_hmac_algos(). |
| data | Required. The message to sign. |
| key | Required. The secret key. |
| binary | Optional. false (default) returns hex. true returns raw bytes. |
Return Value
| Return Value | Description |
|---|
| string | The HMAC as hex, or raw bytes when binary is true. |
PHP Examples
Example 1 — Sign a Message
The same message and key always give the same signature.
<?php
echo hash_hmac('sha256', 'The quick brown fox', 'secret-key'), PHP_EOL;
fb8626bea6af7aca505231f3fa99c27995e34bf32128625aac73ac2a67d8b409
How It Works
- Pass the algorithm.
sha256 is a good default. - Pass the message. This is the data to sign.
- Pass the secret key. Keep it out of public code.
- Get a 64-character signature. It is repeatable.
Example 2 — A Different Key Changes the Result
Only the right key reproduces the signature.
<?php
$a = hash_hmac('sha256', 'data', 'key-one');
$b = hash_hmac('sha256', 'data', 'key-one');
$c = hash_hmac('sha256', 'data', 'key-two');
echo "Same key: ", $a === $b ? "yes" : "no", PHP_EOL;
echo "Other key: ", $a === $c ? "yes" : "no", PHP_EOL;
Same key: yes
Other key: no
How It Works
- Sign twice with one key. The results match.
- Sign once with another key. The result differs.
- Know the point. A signature needs the key.
- In real checks, use `hash_equals()` to compare.
Frequently Asked Questions
It creates a keyed hash of a message. The result proves the message came from someone who knows the key.
hash_hmac(string $algo, string $data, string $key, bool $binary = false): string.
hash() has no key, so anyone can recompute it. hash_hmac() needs the secret key, so only you can create or check the value.
Recompute it from the received data and compare with hash_equals(). This avoids timing leaks.
sha256 is a solid choice. Use sha512 if you need a longer value. Avoid md5 and sha1 in new work.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
8 people found this page helpful