在 C# 和 VB 中使用时使用 HMACSHA256 ComputeHash 的不同结果

Different results from using HMACSHA256 ComputeHash when used in C# and VB

正在 VB 应用程序中创建请求。

Dim unixTimeStamp As Int64
Dim currenttime = DateTime.Now
currenttime = currenttime.AddHours(1)

Dim dt = currenttime.ToUniversalTime
Dim unixEpoch = New DateTime(1970, 1, 1)
unixTimeStamp = (dt.Subtract(unixEpoch)).TotalMilliseconds

Dim nonce = unixTimeStamp
Dim message = String.Format("{0} {1} {2}", ClientId, nonce, Token)

Dim encodin = New ASCIIEncoding
Dim MessageBytes() As Byte = encodin.GetBytes(message)
Dim KeyBytes() As Byte = encodin.GetBytes(apiSecret)

Dim Signature As String
Using myHMACSHA256 As New HMACSHA256(KeyBytes)
Dim hashmessage() As Byte
    hashmessage = myHMACSHA256.ComputeHash(MessageBytes)
    Signature = Convert.ToBase64String(hashmessage)
End Using

Dim strHeader = String.Format("{0} {1} {2} {3}", APIKey, Token, nonce, Signature)
Return strHeader

值在 C# 应用程序中解码,然后重新创建哈希以进行比较。

string msg = string.Format("{0} {1} {2}", clientId, nonce, token);
string result;

var encoding = new ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(privateKey);
byte[] messageBytes = encoding.GetBytes(msg);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
    byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
    result = Convert.ToBase64String(hashmessage);
}

return result == clientSignature;

在此示例中,MessageBytes (vb) 和 messageBytes (c#) 是相同的字节数组。两者的 keyBytes 也是如此。

但是,当调用 hmacsha256.ComputeHash 时,我收到了不同的结果。 两个字节数组长度相同但内容完全不同

我的理解是不同的输入只能给出不同的结果?这里有什么我明显遗漏的吗?

此问题是由于有问题的用户是一个特例,正在与其他开发人员合作以使其插件正常工作。 他们获得了一个新生成的 API 秘密,但未能转发此信息。 上面的代码按预期工作...