我再回答一次,因为你已经改变了整个问题,所以你的新问题有一个新的解决方案。
首先,HMACSHA512 不会给出与您的 php 代码相同的结果。顺便说一句,您的 PHP 生成的哈希是:
41028bb90af31dc6e7fa100a8ceb1e220bfedf67ea723292db9a4e1c14f69c73adf30eeba61ab054cdc91c82f6be2f76dd602392be630b5e99b1f86da1460cbe
为了在 C# 中得到相同的结果,我创建了一个BillieJeansSHA512
类以使哈希等于 PHP。此外,我还使用encoding.GetBytes
将 byte[] 转换为 String 来创建ByteToString
正确转换的方法。
哦,下面的代码不像 PHP 那样简单,但我挑战你或任何人用相同的 PHP 哈希来做这件事!我敢你,我加倍敢于你!我们来看代码:
//These are not default imports, so you need to use it
using System.Text;
using System.Security.Cryptography;
//Before your actual class, you need to make your custom 512
public class BillieJeansSHA512 : HMAC
{
public BillieJeansSHA512(byte[] key)
{
HashName = "System.Security.Cryptography.SHA512CryptoServiceProvider";
HashSizeValue = 512;
BlockSizeValue = 128;
Key = (byte[])key.Clone();
}
}
//Now, there's your actual class
public class HelloWorld{
//First, use this method to convert byte to String like a boss
static string ByteToString(byte[] buff)
{
string sbinary = "";
for (int i = 0; i < buff.Length; i++)
sbinary += buff[i].ToString("x2"); /* hex format */
return sbinary;
}
//Now let's get it started!
public static void Main(String []args){
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
//Your data
var apiSecret = "5432919427bd18884fc2a6e48b65dfba48fd9a1a46e3468b52fadbc6d6b463425";
var data = "payment_currency=USD&group_orders=0&count=100&nonce=1385689989977529";
var endPoint = "/info/orderbook";
String message = endPoint + Convert.ToChar(0) + data;
//Hash will be stored here
String hash = "";
//put your key at your custom 512
BillieJeansSHA512 hmacsha512 = new BillieJeansSHA512(encoding.GetBytes(apiSecret));
//hash'em all
byte[] result = hmacsha512.ComputeHash(encoding.GetBytes(message));
//convert bytes to string
hash = ByteToString(result);
//See it :)
Console.WriteLine(hash);
//Or if you using it at a web-page, this is it.
//Response.Write(hash)
//Now the easy part, convert it to base64
var bytesTo64 = System.Text.Encoding.UTF8.GetBytes(hash);
String hash64 = System.Convert.ToBase64String(bytesTo64);
}
}
……嗯,就是这样。String hash
具有与 PHP 相同的哈希值:
41028bb90af31dc6e7fa100a8ceb1e220bfedf67ea723292db9a4e1c14f69c73adf30eeba61ab054cdc91c82f6be2f76dd602392be630b5e99b1f86da1460cbe
并且String hash64
具有与 PHP 相同的 base64 编码值:
NDEwMjhiYjkwYWYzMWRjNmU3ZmExMDBhOGNlYjFlMjIwYmZlZGY2N2VhNzIzMjkyZGI5YTRlMWMxNGY2OWM3M2FkZjMwZWViYTYxYWIwNTRjZGM5MWM4MmY2YmUyZjc2ZGQ2MDIzOTJiZTYzMGI1ZTk5YjFmODZkYTE0NjBjYmU=