Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MD5 hash in silverlight

I am working on a Windows phone 7 application. I am using this implementation for MD5 hashing in silverlight.

I am using this code -

    protected string GetMD5Hash(string input)
    {
        byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
        MD5Managed md5 = new MD5Managed();
        byte[] hash = md5.ComputeHash(bs);

        StringBuilder sb = new StringBuilder();
        foreach (byte b in bs)
        {
            sb.Append(b.ToString("x2").ToLower());
        }

        return sb.ToString();    
    }

But, I am not getting the correct MD5 hash for the input I provide. I am not sure what is wrong with this code. If anyone has used this implementation for MD5 hashing in silverlight, do you know where have I gone wrong?

like image 633
pavanred Avatar asked Nov 17 '10 15:11

pavanred


2 Answers

You're returning the hex version of the input, not the hash:

foreach (byte b in bs)

should be

foreach (byte b in hash)

(An alternative is to use Convert.ToBase64String(hash) if you don't mind it being in Base64 rather than hex.)

like image 175
Jon Skeet Avatar answered Oct 16 '22 03:10

Jon Skeet


There is already an accepted answer for this, but for others who are using MD5 in Silverlight or Windows Phone, I'm posting a link to another implementation of MD5 that I've had more success with.

I spent several hours beating my head against the wall with the implementation mentioned by the original post, trying to get it working in my Windows Phone project. It was working in some cases and not in others.

Jeff Wilcox's version worked perfectly.

like image 40
Josh Earl Avatar answered Oct 16 '22 03:10

Josh Earl