6

I want to turn the following C# code into PHP.

The C# is:

byte[] operation = UTF8Encoding.UTF8.GetBytes("getfaqs");
byte[] secret = UTF8Encoding.UTF8.GetBytes("Password");

var hmac = newHMACSHA256(secret);
byte[] hash = hmac.ComputeHash(operation);

Which I've turned into this:

$hash = hash_hmac( "sha256", utf8_encode("getfaqs"), utf8_encode("Password"));

Then I have:

var apiKey = "ABC-DEF1234";
var authInfo = apiKey + ":" + hash

//base64 encode the authorisation info
var authorisationHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes(authInfo));

Which I think should be:

$authInfo = base64_encode($apiKey . ":" . $hash);

Or

$authInfo = base64_encode(utf8_encode($apiKey . ":" . $hash));

But not certain, notice this second encoding uses Encoding.UTF8, not UTF8Encoding.UTF8.

What should the PHP code look like?

1
  • 2
    UTF8Encoding.UTF8 and Encoding.UTF8 are equivalent. UTF8Encoding inherits from Encoding so it gains the UTF8 property as a result. Commented Nov 8, 2012 at 23:39

1 Answer 1

6

PHP strings are already (kind of) byte[], php doesn't have any encoding awareness. utf8_encode actually turns ISO-8859-1 to UTF-8, so it's not needed here.

If those strings are literals in your file, that file just needs to be saved in UTF-8 encoding.

Pass true to hash_hmac as 4th parameter and remove those utf8_encode calls:

$hash = hash_hmac( "sha256", "getfaqs", "Password", true );

Also, string concatenation operator is ., so :

$authInfo = base64_encode($apiKey . ":" . $hash);
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for catching the typo - corrected. Still not authenticating, but I think your code is fine & we have additional problems
@jmadsen yes, the C# is not complete. Before this line: var apiKey = "ABC-DEF1234"; var authInfo = apiKey + ":" + hash, hash is still a byte[], so how can it be concatenated to a string?

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.