1

I am using below php code to generate hmac-sha256 and encode it to base64

$data ="sdkfhglkjfdsglfdslkgjdfl;kjsdflk;jsdlgldgweprepoifepiorgi";
$secret = "da851675-c797-4edd-b492-af1c0753e5c0";
$hash = hash_hmac('sha256', $data, $secret);
$base64 = base64_encode($hash);
echo $base64;

but hash is always different from the hash generated from online generators like https://www.javainuse.com/hmac or https://www.devglan.com/online-tools/hmac-sha256-online

same is the case with below javascript code as well.

var data ="sdkfhglkjfdsglfdslkgjdfl;kjsdflk;jsdlgldgweprepoifepiorgi"
var secret = "da851675-c797-4edd-b492-af1c0753e5c0"
function generate_data_hash(data, secret) {
    var hash = CryptoJS.HmacSHA256(data, secret);
    var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
    return hashInBase64
}
console.log(generate_data_hash(data, secret))

any clue on what's going on here?

Gan3i
  • 95
  • 11
  • In the PHP code, the 4th parameter in [`hash_hmac()`](https://www.php.net/manual/en/function.hash-hmac.php) must be passed as `true`, then the result matches that of the CryptoJS code (and those of the linked web sites). – Topaco Mar 18 '23 at 19:17
  • thanks @Topaco that helps but, any idea on why online generators have different results ? little confused on which one should I consider as correct. – Gan3i Mar 18 '23 at 19:23
  • 2
    Both web sites, the CryptoJS code and the *fixed* PHP code return the same (!) value according to my tests, which is (Base64 encoded): `nLdvT5T8HcDuVvZG7ez14nLRN1qpBG3eZZKcciEuYi4=` – Topaco Mar 18 '23 at 19:30

0 Answers0