I am trying to replicate the following code in PHP
, It is example code for an API I have to interface with (The API & Example code is in C#
, My app is in PHP 5.3
). I'm not a C# developer and so am having trouble doing this.
// C# Code I am trying to replicate in PHP
var apiTokenId = 1887;
var apiToken = "E1024763-1234-5678-91E0-T32E4E7EB316";
// Used to authenticate our request by the API (which is in C#)
var stringToSign = string.Empty;
stringToSign += "POST"+"UserAgent"+"http://api.com/post";
// Here is the issue, How can I do the following 3 lines in PHP?
// No "secret key" provided?.. How do I do this in PHP?
var hmacsha1 = new HMACSHA1(new Guid(apiToken).toByteArray());
// Make a byte array with ASCII encoding.
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(stringToSign);
// Finally, 'computeHash' of the above (what does this do exactly?!)
var calculatedSignature = Convert.ToBase64String(hmacsha1.ComputeHash(byteArray));
I've tried many variations using pack()
and other functions I've found online, but without anything to compare it to, I don't know if i've done it right or not.
Can any C# devs run the above code and post the values generated so I can use that to check/test against?
I've tried checking the MSDN to see what these methods do, but am stuck (and not sure if its correct, as I have nothing to compare it to).
PHP Pseudo Code
// Set vars
$apiToken = 'E1024763-1234-5678-91E0-T32E4E7EB316';
$apiTokenId = '1887';
$stringToSign = "POST"."UserAgent"."http://api.com/post";
// HowTo: Build a `byteArray` of our apiToken? (i think)
// C#: var hmacsha1 = new HMACSHA1(new Guid(apiToken).toByteArray());
// HowTo: Convert our $stringToSign to a ASCII encoded `byteArray`?
// C#: byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(stringToSign);
// HowTo: Generate a base64 string of our (`hmacsha1`.ComputeHash(byteArray))
// C#: var calculatedSignature = Convert.ToBase64String(hmacsha1.ComputeHash(byteArray));
This sounds pretty simple and straightforwaard, but I'm not sure what a few of these C# methods do..
What do these C#
methods do/return?
ComputeHash(byteArray)
- Computed to what?.. what is returned?System.Text.Encoding.ASCII.GetBytes(stringToSign);
- What does this return?new HMACSHA1(new Guid(apiToken).toByteArray());
No Secret Key?, what is the key used?
Any resources or help would be much appreciated. I tried variations of other answers on SO, but no joy.
Can I run the 3 lines of code somewhere online (like JSFiddle
but for C#
?) so I can see the output of each line?
Update - Bounty Added
Still having trouble with this, I have managed to test the C#
code in Visual Studio, but am having trouble getting the same hash generated in PHP
.
I would like...
.. the above C#
code (specifically, the 3 lines which create the SHA1
hash) to be converted into PHP (Check out the Pseudo Code
I posted above). I should be able to match the C#
hash using PHP.
If you have any other questions, please ask.