How can I generate a HmacSHA256 signature of a string

How can I generate a HmacSHA256 signature of a string

  1. Blog
  2. 15 November 2026
  3. 2 min read

Stefan Bogdanescu

Founder & Senior Architect

Generating HmacSHA256 Signatures in PHP

Generating a cryptographic signature is a fundamental requirement for building secure APIs, verifying data integrity, and authenticating requests from third-party clients. The HMAC-SHA256 algorithm combines the security of a keyed hash function with the speed of the SHA-256 hashing algorithm. Unlike a simple hash, which anyone can compute if they know the input string, an HMAC requires a secret key to generate. This ensures that only parties possessing the shared secret can produce a valid signature for a given payload.

In PHP, you do not need external libraries to implement this logic; the language provides robust tools within its standard hash and openssl extensions. The most direct approach relies on the built-in hash_hmac function. This method is preferred for general-purpose scripting because it is concise, performant, and avoids the overhead of loading OpenSSL binaries unless necessary.

To generate a signature, you pass three arguments: the data to be signed, the secret key, and the algorithm. The following example demonstrates how to create a signature for a specific string using a hardcoded key for demonstration purposes:

<?php
$data = 'user_action=login&timestamp=1715623401';
$key = 'my_super_secret_key_12345';

// Generate the HMAC-SHA256 signature
$signature = hash_hmac('sha256', $data, $key);

echo "Signature: " . bin2hex($signature); 
// Output: Signature: 8b... (hexadecimal representation)
?>

It is critical to understand the binary nature of raw cryptographic output. The hash_hmac function returns a byte string in binary format. If you attempt to echo this directly or store it in a database expecting text, you will encounter encoding issues or truncated data. Developers must always wrap the result with bin2hex() to convert the binary bytes into a safe hexadecimal string representation. Conversely, if your application receives a signature as a hexadecimal string from an API response, you can reverse this process using pack('H*', $receivedSignature) before passing it to verification functions.

When implementing this in production, the choice of key management is often more significant than the hashing function itself. Never hardcode secrets directly into source files intended for public repositories or shared environments. Instead, retrieve keys from environment variables or a dedicated secrets manager. Furthermore, ensure that the data being hashed follows a deterministic format. If you are signing JSON payloads, serialize them using json_encode with consistent options (such as JSON_UNESCAPED_SLASHES) to avoid signature mismatches caused by whitespace or formatting differences between the client and server.

For complex applications requiring low-level control over the hashing process, the OpenSSL extension offers an alternative via openssl_sign. While functionally equivalent for SHA-256 in most contexts, this method requires creating a resource handle and managing certificates if you move beyond simple symmetric HMACs. However, for standard API authentication where both parties share a static or rotating secret key, the hash_hmac approach remains the industry standard due to its simplicity and reduced surface area for configuration errors.

If your project is built with Laravel, the framework abstracts these details further. You can utilize the Hash facade or leverage Laravel's testing helpers, though understanding the underlying hash_hmac logic ensures you can troubleshoot signature validation failures when they occur in real-world scenarios.

Our network