PHP: How can I generate a HmacSHA256 signature of

2019-01-17 06:27发布

Is there any way to create a HmacSHA256 signature of a string in php?

标签: php hmac
3条回答
Luminary・发光体
2楼-- · 2019-01-17 06:55

Use hash_hmac:

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

Where $secret is your key.

查看更多
别忘想泡老子
3楼-- · 2019-01-17 06:57

The hash_hmac() function could help, here :

Generate a keyed hash value using the HMAC method


For example, the following portion of code :

$hash = hash_hmac('sha256', 'hello, world!', 'mykey');
var_dump($hash);

Gives the following output :

string '07a932dd17adc59b49561f33980ec5254688a41f133b8a26e76c611073ade89b' (length=64)


And, to get the list of hashing algorithms that can be used, see hash_algos().

查看更多
爷的心禁止访问
4楼-- · 2019-01-17 07:09

Here is an example of datatrans transaction signing (swiss e-payment solution) before call PSP with HMAC-SHA-256.

Hope it could help some developers.

$hmacKey    = 30911337928580013;

$merchantId = 1100004624;
$amount     = $total * 100;
$currency   = 'EUR';
$refno      = $orderId;

// HMAC Hex to byte
$secret     = hex2bin("$hmacKey");

// Concat infos
$string     = $merchantId . $amount. $currency . $refno;

// generate SIGN
$sign       = bin2hex(hash_hmac('sha256', $string, $secret)); 

Note: the merchant ID and HMAC key are both from Datatrans documentation available here : https://admin.sandbox.datatrans.com/showcase/doc/Technical_Implementation_Guide.pdf

查看更多
登录 后发表回答