How to generate MD5 hash code for my WinRT app using C#?

21

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

    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:

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

What am I doing wrong here?

c#
.net
windows-runtime
microsoft-metro
asked on Stack Overflow Nov 28, 2011 by Alireza Noori • edited Feb 27, 2012 by Kate Gregory

1 Answer

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;
    }
answered on Stack Overflow Nov 28, 2011 by Alireza Noori • edited Oct 16, 2014 by Alireza Noori

User contributions licensed under CC BY-SA 3.0