In network security and data integrity verification, HMAC (Hash-based Message Authentication Code) is a widely used and effective technique. It combines a hash function and a key to validate the integrity and authenticity of a message. PHP’s built-in hash_hmac() function provides a convenient tool to generate HMAC, but this article will demonstrate how to manually implement HMAC using the more basic hash() function.
The core concept of HMAC is to concatenate the key to the beginning and end of the message, then apply a hash function to the concatenated string. Compared to a simple hash value, HMAC effectively prevents tampering with the message and is more difficult to forge.
The HMAC calculation formula is:
HMAC(key, message) = hash((key ⊕ opad) || hash((key ⊕ ipad) || message))
Where:
|| represents concatenation.
⊕ represents bitwise XOR.
opad is the outer padding, repeated with 0x5c.
ipad is the inner padding, repeated with 0x36.
Here’s how to manually implement HMAC using PHP’s hash() function:
<?php
function hmac_hash($algo, $key, $data) {
$blocksize = 64; // Most hash functions have a block size of 64 bytes
if (strlen($key) > $blocksize) {
$key = hash($algo, $key, true); // If the key is too long, hash it to a fixed-length binary string
}
$key = str_pad($key, $blocksize, chr(0x00)); // Pad the key to the block size
$opad = str_repeat(chr(0x5c), $blocksize);
$inner = $key ^ $ipad;
$outer = $key ^ $opad;
$inner_hash = hash($algo, $inner . $data, true); // Inner hash, output as binary
$hmac = hash($algo, $outer . $inner_hash);
return $hmac;
}
// Test
$key = "secretkey";
$message = "The quick brown fox jumps over the lazy dog";
echo "HMAC-SHA256: " . hmac_hash('sha256', $key, $message);
?>
The above code uses the SHA-256 algorithm to calculate the HMAC for the message and key, returning the result as a hexadecimal string.
It is recommended to use PHP’s built-in hash_hmac() function, which is more efficient and secure.
The key length is generally recommended to match the hash block size.
Using binary output (set the third parameter to true) is helpful for concatenation operations.
HMAC is mainly used for message authentication, so key management should be secure.
Although PHP already provides a convenient hash_hmac() function, understanding and mastering the principles of implementing HMAC with the basic hash() function helps to better understand secure hashing mechanisms and enhance secure programming skills.
For more information, you can visit https://gitbox.net for related resources.