PHP: How can I generate a HmacSHA256 signature of a string

All we need is an easy explanation of the problem, so here it is.

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

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Use hash_hmac:

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

Where $secret is your key.

Method 2

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');

Gives the following output :

string '07a932dd17adc59b49561f33980ec5254688a41f133b8a26e76c611073ade89b' (length=64)

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

Method 3

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 :

Method 4

I can’t answer due to lack of reputation, but @Melomans way in combination with ZPiDER’s answer leads to using only

$hash       = hash_hmac('sha256', $string, $secret);

for a correct Datatrans signing

Method 5

okay to sign your data with hash_hmach
all you need is to do the following

  1. get your secret key
  2. choose a cipher mode or method example sha1,sha256, etc
  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);

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply