2012-03-14 107 views
-1

我正在嘗試使用下面的代碼生成固定長度哈希。固定長度哈希

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位)。有人可以告訴我該怎麼做。

在此先感謝。

回答

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

這工作得很好,但我有一個問題。 (我認爲)但是e兩個10位數字的其餘部分可以相同。所以再次「這將是一個有效的散列」?對不起,如果我困惑的東西。 – 2012-03-14 10:36:04

+0

@MujtabaHassan散列不是「唯一」的。在統計上難以重現(它有各種性質來保證它)。完整的SHA1散列長度爲160位。您拿走的位數越多,找到具有相同散列的第二個對象越容易。 – xanatos 2012-03-14 10:38:52

2

你想從一個散列函數輸出一個8位數字,其最多可以有

LG(2^256)〜78

十進制數字。

您應該考慮更改散列函數或從輸出中捨去最多26位(2^26 = 67108864,2^27 = 134217728 - 9位數字),並舍入爲3個字節(24位),並從中獲取Int32 3個字節。

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); 
} 
+0

在這一行「hashValue.CopyTo(hashPart,230); // 256-26「我得到下面的異常」目標數組不夠長。檢查destIndex和長度以及數組的下限「。。hashValue只有32個字節,所以我將它改爲從9開始而不是230,但異常仍在拋出。 – 2012-03-14 10:24:32

+0

其次,如果我們忽略了一些,你認爲它會是一個有效的散列字節?我對這個想法有些困惑 – 2012-03-14 10:27:07

+0

Aww,抱歉,26位=> 3個字節(24位,因爲4個字節 - 整數可以很容易地多於8位數)向下舍入)更正我的答案和代碼。只是碰撞概率會高得多,無論如何,如果你有8個小數位的限制,你就不會有任何明顯的改進 – 2012-03-14 10:30:51