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?

Peter O.
  • 32,158
  • 14
  • 82
  • 96
jmadsen
  • 3,635
  • 2
  • 33
  • 49
  • 2
    `UTF8Encoding.UTF8` and `Encoding.UTF8` are equivalent. `UTF8Encoding` inherits from `Encoding` so it gains the `UTF8` property as a result. – Dan Herbert Nov 08 '12 at 23:39

1 Answers1

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);
Esailija
  • 138,174
  • 23
  • 272
  • 326
  • thanks for catching the typo - corrected. Still not authenticating, but I think your code is fine & we have additional problems – jmadsen Nov 09 '12 at 07:46
  • @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? – Esailija Nov 09 '12 at 11:34