I have a string in PHP which is being converted to a byte array and hashed.
The string being converted to the byte array looks like:
"g". chr(0) . "poo";
I need to equivalent byte array in C# so i can get the same hash..
EDIT: Here is the FULL problem, resulting hash is not the same.
PHP
$api_secret = '5432919427bd18884fc2a6e48b65dfba48fd9a1a46e3468b52fadbc6d6b463425';
$data = 'payment_currency=USD&group_orders=0&count=100&nonce=1385689989977529';
$endpoint = '/info/orderbook';
$signature = hash_hmac('sha512', $endpoint . chr(0) . $data, $api_secret);
$result = base64_encode($signature);
C#
var apiSecret = "5432919427bd18884fc2a6e48b65dfba48fd9a1a46e3468b52fadbc6d6b463425";
var data = "payment_currency=USD&group_orders=0&count=100&nonce=1385689989977529";
var endPoint = "/info/orderbook";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
String message = endpPoint + Convert.ToChar(0) + data;
var hmacsha512 = new HMACSHA512(encoding.GetBytes(message));
var result = Convert.ToBase64String(hmacsha512.Hash);
I've tried different base64 encoding like:
public static string ByteToString(byte[] buff)
{
string sbinary = "";
for (int i = 0; i < buff.Length; i++)
sbinary += buff[i].ToString("X2"); /* hex format */
return sbinary;
}
but ultimately the issue appears to be the byteArray that is hashed because of the chr(0) php uses.
I'm answering it again, because you have changed the whole question, so there's a new solution for your new question.
First, HMACSHA512 won't give the same result as your php code. By the way, your PHP generated hash is:
To make the same result in C#, I created the
BillieJeansSHA512
class to make the hash equals as PHP. Also instead usingencoding.GetBytes
to convert byte[] to String I have created the methodByteToString
to convert properly.Ow, the following code is not simple as PHP, but I challenge you or anyone to do this simpler with the same PHP's hash! I dare you, I DOUBLE DARE YOU! Let's go to the code:
...well, this is it.
String hash
have the same hash as PHP does:and
String hash64
has the same encoded base64 value that PHP does:He also asked it as
byte
array, it's the most important because have to use char to byte conversion:You can also do the same thing in a single line, if you prefer :)
You can use
Convert.ToChar(Int32)
method to represent unicode values as characters.Usage:
"g" + Convert.ToChar(0) + "poo"