如何使用C#为我的WinRT应用程序生成MD5哈希码?

Ali*_*ori 21 .net c# microsoft-metro windows-runtime

我正在创建一个MetroStyle应用程序,我想为我的字符串生成一个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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

但它会抛出类型异常,System.ArgumentOutOfRangeException并显示以下错误消息:

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

我在这做错了什么?

Ali*_*ori 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;
    }
Run Code Online (Sandbox Code Playgroud)

  • 好吧,而不是使用`ConvertBinaryToString`函数来转换散列二进制数组,我应该使用`EncodeToHexString`函数将数组转换为*Hex*字符串.这是我唯一改变的事情. (2认同)
  • 我将"MD5"替换为[HashAlgorithmNames.Md5](http://msdn.microsoft.com/en-us/library/windows.security.cryptography.core.hashalgorithmnames.md5.aspx). (2认同)