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

时间:2021-07-01 20:19:22

I'm creating a MetroStyle app and I want to generate a MD5 code for my string. So far I've used this:

我正在创建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;
        }
    }

but it throws an exception of type System.ArgumentOutOfRangeException with the following error message:

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

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

目标多字节代码页中不存在Unicode字符的映射。 (HRESULT异常:0x80070459)

What am I doing wrong here?

我在这做错了什么?

1 个解决方案

#1


37  

OK. I've found how to do this. Here's the final code:

好。我发现了如何做到这一点。这是最终的代码:

    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


37  

OK. I've found how to do this. Here's the final code:

好。我发现了如何做到这一点。这是最终的代码:

    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;
    }