我在PHP中有一个字符串,它被转换为字节数组并进行哈希处理.
转换为字节数组的字符串如下所示:
"G".chr(0)."便便";
我需要在C#中等效字节数组,所以我可以得到相同的哈希..
编辑:这是完全问题,导致哈希不一样.
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);
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
我尝试过不同的base64编码,如:
public static string ByteToString(byte[] buff)
{
string sbinary = "";
for (int i = 0; i < …Run Code Online (Sandbox Code Playgroud) 我需要在C#中转换以下php代码:
$res = mac256($ent, $key);
$result = encodeBase64($res);
Run Code Online (Sandbox Code Playgroud)
哪里
function encodeBase64($data)
{
$data = base64_encode($data);
return $data;
}
Run Code Online (Sandbox Code Playgroud)
和
function mac256($ent,$key)
{
$res = hash_hmac('sha256', $ent, $key, true);//(PHP 5 >= 5.1.2)
return $res;
}
Run Code Online (Sandbox Code Playgroud)
我使用以下C#代码:
byte[] res = HashHMAC(ent, key);
string result = System.Convert.ToBase64String(res);
Run Code Online (Sandbox Code Playgroud)
哪里
public byte[] HashHMAC(string ent, byte[] key)
{
byte[] toEncryptArray =System.Text.Encoding.GetEncoding(28591).GetBytes(ent);
HMACSHA256 hash = new HMACSHA256(key);
return hash.ComputeHash(toEncryptArray);
}
Run Code Online (Sandbox Code Playgroud)
这个链接提供完整的php源代码
我也在php中检查了这篇文章hmac_sha256和c#的区别
但结果却不尽相同.
在使用Crypt::Encrypt('secret')Laravel时,我需要在C#中创建相同的结果.我发现这个线程Rijndael 256在c#和php之间加密/解密?
它似乎是我需要的,但我在第三个参数,初始化矢量:(.
Laravel使用Rijndael AES加密数据.所有用户必须输入的是一个秘密密钥,在config文件夹中,它是完全随机的,长度为32个字符.
encyrption方法如下所示:
public function encrypt($value)
{
$iv = mcrypt_create_iv($this->getIvSize(), $this->getRandomizer());
$value = base64_encode($this->padAndMcrypt($value, $iv));
// Once we have the encrypted value we will go ahead base64_encode the input
// vector and create the MAC for the encrypted value so we can verify its
// authenticity. Then, we'll JSON encode the data in a "payload" array.
$mac = $this->hash($iv = base64_encode($iv), $value);
return base64_encode(json_encode(compact('iv', 'value', 'mac')));
}
Run Code Online (Sandbox Code Playgroud)
完整的Encryptor.php可以在这里找到:http://pastebin.com/yfWLPxGn
有什么想法我必须输入以获得相同的结果?:)