Magnus Reuter
Magnus Reuter

Reputation: 43

C# HMAC SHA-256-128 Calculation result not as expected

I'm trying to create a signature to our bank from a specified key but my results is not the same as the info I got from the bank. Can anyone see what I am doing wrong?

Link to bank for reference (text in Swedish)

Example data are inside the citationmarks .. :)

Filedata: "00000000"

Key: "1234567890ABCDEF1234567890ABCDEF"

Expected result: "FF365893D899291C3BF505FB3175E880"

My result: "05CD81829E26F44089FD91A9CFBC75DB"

My code:

        // Using ASCII teckentabell
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

        // Using HMAC-SHA256
        byte[] keyByte = encoding.GetBytes("1234567890ABCDEF1234567890ABCDEF");
        HMACSHA256 hmacsha256 = new HMACSHA256(keyByte);

        byte[] messageBytes = encoding.GetBytes("00000000");
        byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);

        byte[] truncArray = new byte[16];
        Array.Copy(hashmessage, truncArray, truncArray.Length);

        // conversion of byte to string            
        string sigill = ByteArrayToString(truncArray);

        // show sigill
        MessageBox.Show("Sigill:\n" + sigill, "Sigill", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

Upvotes: 4

Views: 1262

Answers (1)

Alex K.
Alex K.

Reputation: 175748

Key is a string of hexadecimal digits representing a binary key, not a string of individual characters.

For the correct output you need to convert it to an array of bytes:

var key = "1234567890ABCDEF1234567890ABCDEF";
byte[] keyByte = new byte[key.Length / 2];

for (int i = 0; i < key.Length; i += 2)
{
   keyByte[i / 2] = Convert.ToByte(key.Substring(i, 2), 16);
}

HMACSHA256 hmacsha256 = new HMACSHA256(keyByte);

byte[] messageBytes = encoding.GetBytes("00000000");
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);

byte[] truncArray = new byte[16];
Array.Copy(hashmessage, truncArray, truncArray.Length);

Upvotes: 4

Related Questions