Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

hash_hmac

Calculates a signature of data with a secret key.

Syntax

hash_hmac(string $algo, string $data, string $key, bool $binary = false): string

Parameters

ParameterTypeDescription
$algostringThe algorithm, such as `sha256`.
$datastringThe data to sign.
$keystringThe secret key.
$binaryboolOptional. `true` returns raw bytes.

Return value

stringThe signature in hexadecimal.

Examples

Signing and verifying:

<?php
 
$secret = 'my-secret-key';
$payload = '{"order":42}';
 
$signature = hash_hmac('sha256', $payload, $secret);
 
var_dump(hash_equals($signature, hash_hmac('sha256', $payload, $secret)));
var_dump(hash_equals($signature, hash_hmac('sha256', '{"order":43}', $secret)));

Output:

bool(true)
bool(false)

Notes

This is how you check that a request from a payment system or another service is not forged. Compare signatures only with hash_equals().

See also

  • hash — Returns the hash of a string using a chosen algorithm.
  • hash_equals — Compares two strings in constant time.
  • random_bytes — Returns cryptographically secure random bytes.

In the tutorial

  • Security — The basics of PHP site security — XSS and escaping, SQL injection, password hashing, CSRF tokens and validating input.

Thanks for reading!

Donate to the site — we work hard for you.