Using HMAC Verification in PHP

By: Andi, Stig and Derick Printer Friendly Format    

If you need to prevent bad guys from tampering with variables passed in the URL (such as for a redirect as shown previously, or for links that pass special parameters to the linked script), you can use a hash, as shown in the following script:

<?php

function create_parameters($array)

{

$data = '';

$ret = array();

/* For each variable in the array we a string containing

* "$key=$value" to an array and concatenate

* $key and $value to the $data string. */

foreach ($array as $key => $value) {

$data .= $key . $value;

$ret[] = "$key=$value";

}

/* We also add the md5sum of the $data as element

* to the $ret array. */

$hash = md5($data);

$ret[] = "hash=$hash";

return join ('&amp;', $ret);

}

echo '<a href="script.php?'. create_parameters(array('cause' =>'vars')).'">err!</a>';

?>

Running this script echoes the following link:

<a href='script.php?cause=vars&hash=8eee14fe10d3f612589cdef079c025f6'>err!</a>

However, this URL is still vulnerable. An attacker can modify both the variables and the hash. We must do something better. We’re not the first ones with this problem, so there is an existing solution: HMAC (Keyed-Hashing for Message Authentication). The HMAC method is proven to be stronger cryptographically, and should be used instead of home-cooked validation algorithms.

The HMAC algorithm uses a secret key in a two-step hashing of plain text (in our case, the string containing the key/value pairs) with the following steps:

  1. If the key length is smaller than 64 bytes (the block size that most hashing algorithms use), we pad the key to 64 bytes with \0s; if the key length is larger than 64, we first use the hash function on the key and then pad it to 64 bytes with \0s.

  2. We construct opad (the 64-byte key XORed with 0x5C) and ipad (the 64-byte key XORed with 0x36).

  3. We create the "inner" hash by running the hash function with the parameter ipad . plain text. (Because we use an "iterative" hash function, like md5() or sha1(), we don’t need to seed the hash function with our key and then run the seeded hash function over our plain text. Internally, the hash will do the same anyway, which is the reason we padded the key up to 64 bytes).

  4. We create the "outer" hash by running the hash function over opad inner_result — that is, using the result obtained in step 3.

Here is the formula to calculate HMAC, which should help you understand the calculation:

H(K XOR opad, H(K XOR ipad, text))

With

  • H. The hash function to use

  • K. The key padded to 64 bytes with zeroes (0x0)

  • opad. The 64 bytes of 0x5Cs

  • ipad. The 64 bytes of 0x36s

  • text. The plain text for which we are calculating the hash



Ask a Question



Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial