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?

Kate Gregory
  • 18,808
  • 8
  • 56
  • 85
Alireza Noori
  • 14,961
  • 30
  • 95
  • 179

1 Answers1

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;
    }
Alireza Noori
  • 14,961
  • 30
  • 95
  • 179
  • 1
    You may want to explain what you changed and why. – BoltClock Nov 28 '11 at 17:42
  • 2
    Well instead of using `ConvertBinaryToString` function to convert the hashed binary array I should've used the `EncodeToHexString` function to convert the array to the *Hex* string. That is the only thing I changed. – Alireza Noori Nov 28 '11 at 17:54
  • @AlirezaNoori Didnt get the refrence for HashAlgorithmProvider – user1006544 Jan 17 '12 at 08:42
  • It's `Windows.Security.Cryptography.Core.HashAlgorithmProvider`. Just add `using Windows.Security.Cryptography` – Alireza Noori Dec 13 '13 at 10:17
  • On Windows 8.1 (Universal Apps) The class static Windows.Security.Cryptography.Core.HashAlgorithmNames contains names of algorithms. – hmadrigal Sep 08 '14 at 23:33
  • 2
    I would replace "MD5" to [HashAlgorithmNames.Md5](http://msdn.microsoft.com/en-us/library/windows.security.cryptography.core.hashalgorithmnames.md5.aspx). – Alexander.Ermolaev Oct 16 '14 at 12:31
  • What a bloody pain in the arse that was. Thanks loads for the solution. – djack109 Oct 01 '15 at 21:07
  • Hi, if i want to compare with the password in my Database i need to perform the same thing to encrypt and then tuck the result to compare ? Thanks! –  Aug 22 '16 at 02:38
  • This code worked great for me for generating Sha256 hash, just changed the algorithm. Thanks. – raddevus Sep 06 '16 at 02:38