固定长度哈希

时间:2012-03-14 09:55:30

标签: c# hash

我正在尝试使用以下代码生成固定长度哈希。

public int GetStableHash(string s)
        {
            string strKey = "myHashingKey";
            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(strKey);
            byte[] contentBuffer = UE.GetBytes(s);
            // Initialize the keyed hash object.
            HMACSHA256 myhmacsha256 = new HMACSHA256(key);
            byte[] hashValue = myhmacsha256.ComputeHash(contentBuffer);
            return BitConverter.ToInt32(hashValue,0);
        }

它给了我这样的输出。

  

-1635597425

我需要一个正数固定长度(8位数)。有人可以告诉我该怎么做。

提前致谢。

2 个答案:

答案 0 :(得分:2)

您正在尝试从哈希函数输出中获取一个8位数字,该数字最多可以

lg(2 ^ 256)~78

十进制数字。

您应该考虑更改散列函数或者最多替换26位(2 ^ 26 = 67108864,2 ^ 27 = 134217728 - 已经有9位数)从输出向下舍入到3个字节(24位)并从这些位置获取Int32字节。

public int GetStableHash(string s)
{
    ...
    byte[] hashValue = myhmacsha256.ComputeHash(contentBuffer);
    byte[] hashPart = new byte[3];
    hashValue.CopyTo(hashPart, 29); // 32-3
    return System.BitConverter.ToInt32(hashPart, 0);
}

答案 1 :(得分:1)

unchecked
{
    int num = BitConverter.ToInt32(hashValue,0);

    if (num < 0)
    {
        num = -num;
    }

    num %= 100000000;
}

我正在使用unchecked因为否则-int.MinValue会中断(但请注意,通常程序是使用unchecked“标记”“编译的”)

代码意味着:

    unchecked

don't do overflow controls

    if (num < 0)
    {
        num = -num;
    }

make the number positive if negative

    num %= 100000000;

take the remainder (that has 0-8 digits)

更短:

return unchecked((int)((uint)BitConverter.ToInt32(hashValue,0) % 100000000));
相关问题