繁体   English   中英

C# HMACSHA256 在 PHP 中等效

[英]C# HMACSHA256 equivalent in PHP

我正在尝试使用hash_hmac sha256php创建数字签名,但问题是结果与用C#编写的api结果不等价。 这是C#代码:

public static String createSignature(string apiSecret, long nonce, string customerId, string apiKey)
{
    byte[] keyBytes = StringToByteArray(apiSecret);

    using (HMACSHA256 hmac = new HMACSHA256(keyBytes))
    {
        byte[] data = hmac.ComputeHash(Encoding.UTF8.GetBytes(nonce + customerId + apiKey));
        return bytesToHex(data);
    }
}

public static String bytesToHex(byte[] bytes)
{
    char[] hexArray = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    char[] hexChars = new char[bytes.Length * 2];

    for (int j = 0; j < bytes.Length; ++j)
    {
        int v = bytes[j] & 255;
        hexChars[j * 2] = hexArray[(uint)v >> 4];
        hexChars[j * 2 + 1] = hexArray[v & 15];
    }

    return new String(hexChars);
}

public static byte[] StringToByteArray(string hex)
{
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}

这是我的php代码:

$string = $nonce.$customer.$api_key;
$signature = hash_hmac("sha256", utf8_encode($string), utf8_encode($api_secret));

我只能更改php代码以匹配C#结果。 到目前为止,我使用utf8_encodebase64_encode和简单string作为hash_hmac函数的输入,它们的结果都与C#版本不同。
注意:为了测试,我在phpC#使用了固定的noncecustomerapi_keysecret
ps:我知道网站上有很多关于这个主题的有效解决方案的问题。 我尝试了其中的大部分,但没有一个对我有用。

这应该可以解决问题:

string result = createSignature("AABBCC", 0, "1", "mykey");

// FFB95E1E991734F1C2AE0B7C7ACECFAA5D3BEE943189539C3439B344A9A82E39
Console.WriteLine(result);
<?php

$nonce = 0;
$customer = '1';
$api_key = 'mykey';
$api_secret = hex2bin('AABBCC');

$string = $nonce . $customer . $api_key;
$signature = strtoupper(hash_hmac('sha256', $string, $api_secret));

// FFB95E1E991734F1C2AE0B7C7ACECFAA5D3BEE943189539C3439B344A9A82E39
echo $signature;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM