HMAC-SHA-256 in PHP

There's a couple of things to notice:

  1. Your key is base64-encoded. You have to decode it before you could use it with php functions. That's the most important thing you have missed.
  2. Mhash is obsoleted by Hash extension.
  3. You want output to be encoded in a custom fashion, so it follows that you need raw output from hmac function (php, by default, will hex-encode it).

So, using hash extension this becomes:

$key = "LRH9CAkNs-zoU3hxHbrtY0CUUcmqzibPeN7x6-vwNWQ=";
$str = "kki98hkl-u5d0-w96i-62dp-xpmr6xlvfnjz:20151110171858:b2c13532-3416-47d9-8592-a541c208f755:hKSeRD98BHngrNa51Q2IgAXtoZ8oYebgY4vQHEYjlmzN9KSbAVTRvQkUPsjOGu4F";

function encode($data) {
    return str_replace(['+', '/'], ['-', '_'], base64_encode($data));
}

function decode($data) {
    return base64_decode(str_replace(['-', '_'], ['+', '/'], $data));
}

$binaryKey = decode($key);

var_dump(encode(hash_hmac("sha256", $str, $binaryKey, true)));

Outputs:

string(44) "P-WgZ8CqV51aI-3TncZj5CpSZh98PjZTYxrvxkmQYmI="

Simply use hash_hmac() function available in PHP.

Example :

hash_hmac('sha256', $string, $secret);

Doc here : http://php.net/manual/fr/function.hash-hmac.php

Tags:

Php

Hmac