Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 837
Alireza Noori Avatar asked Nov 28 '11 16:11

Alireza Noori


1 Answers

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;
    }
like image 142
Alireza Noori Avatar answered Oct 12 '22 22:10

Alireza Noori