SoFunction
Updated on 2025-03-07

Solutions for different md5 calculation results of C# and PHP

The problem reappears

This API was used to activate the Lyra application at that time, so I opened Lyra and tried it, but found that everything was normal, so I could rule out the problem on the server.

Release the source code that caused the error (fromMSDN):

public string CalculateMD5Hash(string input)
{
  // step 1, calculate MD5 hash from input
  MD5 md5 = .();
  byte[] inputBytes = (input);
  byte[] hash = (inputBytes);
  // step 2, convert byte array to hex string
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < ; i++)
  { (hash[i].ToString(“X2”));
  }
  return ();
}

substance

There are many versions of MD5, but this code is not wrong, but the md5 function of php returns 32-bit lowercase by default, while the above paragraph returns 16-bit lowercase

So I can find a way to change this func to 32-bit lowercase output

public static String md5(String s)
{
  MD5 md5 = new MD5CryptoServiceProvider();
  byte[] bytes = .(s);
  bytes = (bytes);
  ();

  string ret = "";
  for (int i = 0; i < ; i++)
  {
    ret += (bytes[i], 16).PadLeft(2, '0');
  }
  return (32, '0');
}

Summarize

The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate.