2010-10-10 52 views
4

有人可以幫助我將以下兩行python轉換爲C#。將Python中的SHA哈希計算轉換爲C#

hash = hmac.new(secret, data, digestmod = hashlib.sha1) 
key = hash.hexdigest()[:8] 

其餘的看起來是這樣的,如果你位數的:

#!/usr/bin/env python 

import hmac 
import hashlib 


secret = 'mySecret'  
data = 'myData' 

hash = hmac.new(secret, data, digestmod = hashlib.sha1) 
key = hash.hexdigest()[:8] 

print key 

感謝

回答

6

您可以使用HMACSHA1類來計算哈希:

class Program 
{ 
    static void Main() 
    { 
     var secret = "secret"; 
     var data = "data"; 
     var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(secret)); 
     var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(data)); 
     Console.WriteLine(BitConverter.ToString(hash)); 
    } 
} 
+0

非常感謝你許多! – Sara 2010-10-10 09:12:51

+0

爲了打印密鑰,我添加了:string key = string.Empty; foreach(散列中的字節b) key + = b.ToString(「X2」); } MessageBox.Show(key); – Sara 2010-10-10 09:13:15

+4

或者你可以'BitConverter.ToString(hash).Replace(「 - 」,string.Empty)'。 – 2010-10-10 09:14:14