0

I don't know C# and I must port a small function into PHP. I broke down all the code into a simple example showing the issue.

Here is the C# portion where a sha1 hash is being base64 encoded:

HMACSHA1 hmacTest = new HMACSHA1();
hmacTest.Key = Convert.FromBase64String(identity);

byte[] sha1 = hmacTest.ComputeHash(new byte[]{0, 0, 0, 0, 86, 107, 192, 162, 99, 111, 110, 102});

Console.WriteLine(string.Concat(sha1.Select(b => b.ToString("x2"))));
Console.WriteLine(Convert.ToBase64String(sha1, Base64FormattingOptions.None));
// sha1: 02628928a3a2ab831a769f2fd64a3bae4036265f
// encoded: AmKJKKOiq4Madp8v1ko7rkA2Jl8=

Here is the PHP portion showing a different result, though the sha1 matches

$key = base64_decode($identity);
$data = call_user_func_array("pack", array_merge(array("C*"), array(0, 0, 0, 0, 86, 107, 192, 162, 99, 111, 110, 102)));

$sha1 = hash_hmac('sha1', $data, $key);

var_dump($sha1, base64_encode($sha1));
// sha1: 02628928a3a2ab831a769f2fd64a3bae4036265f
// encoded: MDI2Mjg5MjhhM2EyYWI4MzFhNzY5ZjJmZDY0YTNiYWU0MDM2MjY1Zg==

I must modify the PHP portion to match. I'm thinking it's an encoding issue. Or possibly that in C# ToBase64String is not being passed a string version of the sha1. How would I replicate this in PHP if that is why it's different?

1 Answer 1

3

In your C# code sha1 is a byte array but in your PHP code I think your sha1 is a string

So Give this snippet a try:

$sha1 = hash_hmac('sha1', $data, $key,TRUE);

with the 4th param you'll get raw binary instead of string.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh my, that was so easy. Forgot all about the 4th param. Thank you so much.
Thank you for this! I found this answer after 4 hours of digging around and Googleing.. I had a similar problem which drove me bananas :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.