Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the PHP equivalent of this C# encoding code?

Tags:

c#

php

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?

like image 993
jmadsen Avatar asked Nov 08 '12 23:11

jmadsen


1 Answers

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);
like image 79
Esailija Avatar answered Sep 25 '22 08:09

Esailija