Php: How to Generate a Hmacsha256 Signature of a String

How can I generate a HmacSHA256 signature of a string

Use hash_hmac:

$sig = hash_hmac('sha256', $string, $secret)

Where $secret is your key.

HMAC sha256 in PHP does not return output in hex and with dash (-)

Output format for hash hmac sha256 on php is not exactly identical with c#. Here is example of php's hash hmac sha256: https://stackoverflow.com/a/2708000/3706717

string '07a932dd17adc59b49561f33980ec5254688a41f133b8a26e76c611073ade89b' (length=64)

You just need to convert it to c#'s format

  • add a dash every 2 character
  • transform to uppercase
$string = '07a932dd17adc59b49561f33980ec5254688a41f133b8a26e76c611073ade89b';
$string = strtoupper($string);
$arr = str_split($string, 2);
$string = implode("-", $arr);
var_dump($string);

output:

string(95) "07-A9-32-DD-17-AD-C5-9B-49-56-1F-33-98-0E-C5-25-46-88-A4-1F-13-3B-8A-26-E7-6C-61-10-73-AD-E8-9B"

assuming the plaintext and secret is the same, the output of both c# and php (transformed by code above) should be equal string.

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="

C# HMACSHA256 equivalent in PHP

This should do the trick:

string result = createSignature("AABBCC", 0, "1", "mykey");

// FFB95E1E991734F1C2AE0B7C7ACECFAA5D3BEE943189539C3439B344A9A82E39
Console.WriteLine(result);
<?php

$nonce = 0;
$customer = '1';
$api_key = 'mykey';
$api_secret = hex2bin('AABBCC');

$string = $nonce . $customer . $api_key;
$signature = strtoupper(hash_hmac('sha256', $string, $api_secret));

// FFB95E1E991734F1C2AE0B7C7ACECFAA5D3BEE943189539C3439B344A9A82E39
echo $signature;

Using JavaScipt for calculating HMAC-SHA256 signature

The key is processed as a hexadecimal encoded string in the PHP and Java code, but not in the NodeJS code. To do the same in the NodeJS code, replace 'abc123' with Buffer.from('abc123', 'hex') in the createHmac call.



Related Topics



Leave a reply



Submit