2016-02-19 44 views
0

使用SHA1給定的鹽字節數組我有一個隨機生成byte陣列:哈希字節陣列,以在UWP

Random random = new Random(); 
var bytes = new byte[32]; 
random.NextBytes(myBytes); 

我想用SHA1與給定的字節數組像例如散列它:

public static readonly sbyte[] salt = new sbyte [] { 82, 122, 43, 30, 
                  -47, 97, 4,-124, 
                  -31, -63, -108, 69, 
                  -83, -86, -125, 88, 
                  -98, -77, 111, 79, 
                  -71, -73, 100, 106, 
                  8, -20, -95, -27, 
                  38, -32, -61, 88}; 

我真的不與這個經歷,我有這樣的java代碼,我想在C#寫在UWP平臺:

public static byte []computeKey(byte[] bytes) throws NoSuchAlgorithmException 
{ 
    byte[] salt = { 82,122, 43, 30,-47, 97, 4,-124,-31,-63,-108, 69,-83,-86,-125, 88,-98,-77,111, 79,-71,-73,100,106, 8,-20,-95,-27, 38,-32,-61, 88}; 
    MessageDigest digester = MessageDigest.getInstance("SHA1"); 
    digester.update(bytes, 0, bytes.length); 
    digester.update(salt, 0, salt.length); 
    byte[] digest = digester.digest(); 
    return digest; 
} 

我想在C#UWP實現這一目標,我會發現,這是可行的.Net使用System.Security.Cryptography使用TransformBlock方法(不知道但究竟如何),問題是,在UWP它是完全不同的,使用Windows.Security.Cryptography ,沒有太多的選擇,嘗試了一些路徑,但沒有清楚,任何提示如何實現?

回答

0

試試這個:

byte[] salt = { 82, 122, 43, 30, 47, 97, 4, 124, 31, 63, 108, 69, 83, 86, 125, 88, 98, 77, 111, 79, 71, 73, 100, 106, 8, 20, 95, 27, 38, 32, 61, 88 }; 
var message = "message"; 
var computedBytes = HmacSha1Sign(salt, message); 

使用此項功能:

public static byte[] HmacSha1Sign(byte[] keyBytes, string message) 
{ 
    var messageBytes = Encoding.UTF8.GetBytes(message); 
    MacAlgorithmProvider objMacProv = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1"); 
    CryptographicKey hmacKey = objMacProv.CreateKey(keyBytes.AsBuffer()); 
    IBuffer buffHMAC = CryptographicEngine.Sign(hmacKey, messageBytes.AsBuffer()); 
    return buffHMAC.ToArray(); 
}