【问题标题】:C# HMAC SHA-256-128 Calculation result not as expectedC# HMAC SHA-256-128 计算结果与预期不符
【发布时间】:2014-09-18 11:21:58
【问题描述】:

我正在尝试使用指定的密钥为我们的银行创建签名,但我的结果与我从银行获得的信息不同。谁能看到我做错了什么?

链接到bank 以供参考(瑞典文文本)

示例数据在引用标记内.. :)

文件数据:“00000000”

密钥:“1234567890ABCDEF1234567890ABCDEF”

预期结果:“FF365893D899291C3BF505FB3175E880”

我的结果:“05CD81829E26F44089FD91A9CFBC75DB”

我的代码:

        // 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);

【问题讨论】:

  • key是字节的字符串还是十六进制字符串表示? (即密钥字节 1 = 0x12)
  • 我得到的文档显示:HMAC-SHA256-128 中的密钥在处理中表示为一系列 32 个十六进制数字。数字代表 4 位组,因此可以说密钥值包含 128 位。

标签: c# hmac sha256


【解决方案1】:

Key 是代表二进制密钥的十六进制数字字符串,而不是单个字符的字符串。

为了得到正确的输出,您需要将其转换为字节数组:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 2012-07-07
    • 2018-03-18
    • 2016-03-29
    • 2016-08-03
    • 1970-01-01
    • 2013-01-09
    相关资源
    最近更新 更多