2012-10-23 27 views
0

好吧,我正在使用一個原始的SHA1哈希來播種一個Mersenne Twister僞隨機數發生器 生成器給我的選項可以用無符號long或數組的無符號多頭重寫一個無符號的字符數組到一個無符號的長數組

我使用SHA1類給我的哈希值作爲無符號的字符

我想我可以重鑄這個數組字符來多頭陣列以獲得工作種子的20字節數組,但我怎樣才能知道最終的長陣列是多久?

示例代碼:

CSHA1 sha1; 
sha1.Update((unsigned char*)key, size_key); 
sha1.Final(); 
unsigned char* hash; 
sha1.GetHash(hash); 

// Seed the random with the key 
MTRand mt((unsigned long*)hash, <size of array of longs>); 

我希望沒有數據丟失(如在任何字節脫落),因爲我需要這個來保持加密安全

回答

1

你可以說

sizeof(unsigned long)/sizeof(unsigned char) 

以獲得長的八位字節數。

但是,簡單鑄造有兩個潛在的問題。

首先,字符數組可能沒有正確對齊。在某些處理器上,這可能會導致陷阱。在其他方面它只會減緩執行速度。

其次,如果程序必須在不同的架構上以相同的方式工作,則需要輸入字節順序問題。

您可以通過將字節顯式複製到long數組中來解決這兩個問題。未經測試的代碼:

const int bytes_per_long = sizeof(unsigned long)/sizeof(unsigned char); 
unsigned long hash_copy[key_length_in_bytes/bytes_per_long]; 
int i_hash = 0; 
for (int i_copy = 0; i_copy < sizeof hash_copy/sizeof hash_copy[0]; i_copy++) { 
    unsigned long b = 0; 
    for (int i_byte = 0; i_byte < bytes_per_long; i_byte++) 
    b = (b << 8) | hash[i_hash++]; 
    hash_copy[i_copy] = b; 
} 
// Now use hash_copy. 
+1

這是如何解決字節順序問題的? – aib

+0

你是對的。謝謝。我有一個明確的單詞副本(我剛剛替換)並將其刪除。這是一個漫長的一天。 – Gene

+0

它肯定是。 – aib

1

您可以使用len_of_chars * sizeof(char)/sizeof(long),其中len_of_chars大概是20

+0

sizeof(char)始終爲1. – aib

+0

@aib:當然,但如果你將它放在那裏,它會讓你更明白你在做什麼。無論如何,編譯器會將表達式評估爲常量。 –

+0

嗯,真的,那。 – aib

0

Your library似乎假定32位unsigned long S,所以沒有[更多]傷害你做同樣的。事實上,我會盡可能地假定8位unsigned char,甚至可能是無襯墊的小端代表。所以你可以使用簡單的演員(雖然我會使用reinterpret_cast),或者@ Gene的memcpy樣本進行比對。

移植的代碼*,但是,應該使用<cstdint>,其中的uint#_t類型和分段,按值拷貝轉換:

uint32_t littleEndianInt8sToInt32(uint8_t bytes[4]) { 
    return bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24); 
} 

...和更好的名字。對不起,天色已晚在這裏:)

*:雖然,當然,stdint本身是不是很便攜(> = C++ 11)和精確寬度類型不能保證在它。具有諷刺意味的。

+0

與問題無關,但補充了答案:[Portable C++ 03 Exact Width Types](http://stackoverflow.com/questions/1481733/portable-c-03-exact-width-types) – aib

相關問題