Friday, October 2, 2009

MD5 in PHP and in C#

I use MD5 for adding security for non secured connection between a client and a server. Though the information is not classified, it is important that it won't be changed by MITM.
The client needs to send data to the server. Both the client and the server have a common secret password. The server has a public integer counter. Each time a message sent I do: counter++;
When the client wants to send the data, he must add a signature which is the following:
md5(counter + secret_password + data)
or in C# terms:


        public static Encoding encoding = Encoding.Default;

        public static string ComputeMD5(string str)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            return Convert.ToBase64String(md5.ComputeHash(encoding.GetBytes(str)));
        }


        ComputeMD5(counter + secret_password + data);




On the server side, we compute the same thing in PHP:

base64_encode(md5($counter . $secret . $data, true)));


Unfortunately, sometimes it works and sometimes not. The result of MD5 is different in the two sites, though I verified the data is the same. It took me a day to realize the problem was special characters (I had the character 0xa0 instead of 0x0a by mistake), only to find out it's not the only problem, and there are still some problematic cases.
I'm sure it's a simple problem, and I don't see the solution due to the fact I'm awake for over 24 hours now. I'm pretty sure it has something to do with that encoding thing I had to use. I'm going to look into it tomorrow.

No comments:

Post a Comment