简体   繁体   English

PHP:如何生成字符串的 HmacSHA256 签名

[英]PHP: How can I generate a HmacSHA256 signature of a string

有没有办法在php中创建一个字符串的HmacSHA256签名?

Use hash_hmac :使用hash_hmac

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

Where $secret is your key. $secret是你的钥匙。

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()

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

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 签名

okay to sign your data with hash_hmach all you need is to do the following可以使用 hash_hmach 对您的数据进行签名,您只需要执行以下操作

  1. get your secret key获取你的秘钥
  2. choose a cipher mode or method example sha1,sha256, etc选择密码模式或方法示例 sha1、sha256 等
  3. create a variable that will hold your encrypted data call it whatever you like Therefore the code will look like this创建一个变量来保存您的加密数据,您可以随意调用它因此代码将如下所示

 $signData= hash_hmac("sha256",$dataToBeSigned,$yourSecretKey);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM