Search code examples
c#vb.nethashencodinghmacsha1

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


The request is being created in a VB application.

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

Values are decoded in a C# application and then the hash is recreated for comparison.

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;

In this example, MessageBytes (vb) and messageBytes (c#) are identical byte arrays. The same goes for keyBytes for both.

However, when hmacsha256.ComputeHash is called, I am receiving different results. Both byte arrays are the same length but the contents are completely different.

My understanding is that different results can only be given for different inputs? Is there anything obvious here that I'm missing?


Solution

  • This issue was caused by the user in question being a special case that was working with another developer to get their plugin working. They had been given a newly generated API secret and had failed to relay this information. The code above works as intended...