21

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

但它会引发类型异常,System.ArgumentOutOfRangeException并带有以下错误消息:

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

我在这里做错了什么?

4

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;
    }
于 2011-11-28T17:35:53.477 回答