2011-11-28 39 views
21

我正在創建一個MetroStyle應用程序,我想爲我的字符串生成一個MD5代碼。到目前爲止,我用這個:如何使用C#爲我的WinRT應用程序生成MD5哈希碼?

public static string ComputeMD5(string str) 
    { 
     try 
     { 
      var alg = HashAlgorithmProvider.OpenAlgorithm("MD5"); 
      IBuffer buff = CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8); 
      var hashed = alg.HashData(buff); 
      var res = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, hashed); 
      return res; 
     } 
     catch (Exception ex) 
     { 
      return null; 
     } 
    } 

但它拋出System.ArgumentOutOfRangeException類型與以下錯誤消息的異常:

No mapping for the Unicode character exists in the target multi-byte code page. (Exception from HRESULT: 0x80070459)

我在做什麼錯在這裏?

+1

哪一行會引發異常? –

+0

'return res;'之前的行我的意思是'var res = ...' –

回答

37

好的。我發現如何做到這一點。這是最終的代碼:

public static string ComputeMD5(string str) 
    { 
     var alg = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5); 
     IBuffer buff = CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8); 
     var hashed = alg.HashData(buff); 
     var res = CryptographicBuffer.EncodeToHexString(hashed); 
     return res; 
    } 
+1

你可能想解釋你改變了什麼,爲什麼。 – BoltClock

+2

那麼,我應該使用'EncodeToHexString'函數將數組轉換爲* Hex *字符串,而不是使用ConvertBinaryToString函數來轉換哈希二進制數組。這是我改變的唯一的事情。 –

+0

@AlirezaNoori沒有得到HashAlgorithmProvider的參考 – user1006544