2011-11-28 18 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