mehrdadep
mehrdadep

Reputation: 1019

C# HMACSHA256 equivalent in PHP

I'm trying to use hash_hmac sha256 to create digital signature in php but the problem is the result is not equivalent with api result that is written with C#. here is the C# code:

public static String createSignature(string apiSecret, long nonce, string customerId, string apiKey)
{
    byte[] keyBytes = StringToByteArray(apiSecret);

    using (HMACSHA256 hmac = new HMACSHA256(keyBytes))
    {
        byte[] data = hmac.ComputeHash(Encoding.UTF8.GetBytes(nonce + customerId + apiKey));
        return bytesToHex(data);
    }
}

public static String bytesToHex(byte[] bytes)
{
    char[] hexArray = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    char[] hexChars = new char[bytes.Length * 2];

    for (int j = 0; j < bytes.Length; ++j)
    {
        int v = bytes[j] & 255;
        hexChars[j * 2] = hexArray[(uint)v >> 4];
        hexChars[j * 2 + 1] = hexArray[v & 15];
    }

    return new String(hexChars);
}

public static byte[] StringToByteArray(string hex)
{
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}

and here is my php code:

$string = $nonce.$customer.$api_key;
$signature = hash_hmac("sha256", utf8_encode($string), utf8_encode($api_secret));

I can change the php code only to match the C# result. so far I used utf8_encode, base64_encode and simple string as inputs in hash_hmac functon which all have different results from C# version.
Note: for testing I used fixed nonce, customer and api_key and secret in php and C#
p.s: I know there are multiple questions with working solutions on the site about this subject. I tried most of them and none of them worked for me.

Upvotes: 0

Views: 659

Answers (1)

odan
odan

Reputation: 4962

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;

Upvotes: 2

Related Questions