PHP:如何生成字符串的 HmacSHA256 签名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2707967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: How can I generate a HmacSHA256 signature of a string
提问by tarnfeld
Is there any way to create a HmacSHA256 signature of a string in php?
有没有办法在php中创建一个字符串的HmacSHA256签名?
回答by Sebastian Paaske T?rholm
回答by Pascal MARTIN
The hash_hmac()function could help, here :
该hash_hmac()功能可以提供帮助,在这里:
Generate a keyed hash value using the HMAC method
使用 HMAC 方法生成键控哈希值
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().
而且,要获得可以使用的散列算法列表,请参阅hash_algos()。
回答by Meloman
Here is an example of datatrans transaction signing(swiss e-payment solution) before call PSP with HMAC-SHA-256.
这是在使用HMAC-SHA-256调用 PSP 之前的datatrans 交易签名示例(瑞士电子支付解决方案)。
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
注意:商家 ID 和 HMAC 密钥均来自此处提供的 Datatrans 文档:https://admin.sandbox.datatrans.com/showcase/doc/Technical_Implementation_Guide.pdf
回答by 3tl4m
I can't answer due to lack of reputation, but @Melomans way in combination with ZPiDER's answer leads to using only
由于缺乏声誉,我无法回答,但@Melomans 方式与 ZPiDER 的回答相结合导致仅使用
$hash = hash_hmac('sha256', $string, $secret);
for a correct Datatrans signing
正确的 Datatrans 签名

