The method of generating MD5 Hash Code in C the same as PHP

  • 2020-12-09 00:48:37
  • OfStack

Recently, an existing system was modified with C#. The system was previously made with PHP, and the administrator in the background logged in with MD5 encryption algorithm. In PHP, MD5 encryption for a string is as simple as one line of code:

 
md5("Something you want to encrypt.") 

Call the md5() method directly and pass in the MD5 encrypted string to get the returned hash code. There should be a corresponding algorithm in C#. Isn't it? I first tried the following code and the result is not the same as hash code.
 
public static string MD5(string stringToHash) 
{ 
return FormsAuthentication.HashPasswordForStoringInConfigFile(stringToHash, "md5"); 
} 

So, we had to borrow MD5CryptoServiceProvider objects from C# to write our own code for the transformation.

1. Instantiate the MD5CryptoServiceProvider object

2. Converts the string to an byte array

3. Use the ComputeHash() method of MD5CryptoServiceProvider object to encrypt the byte array and return the converted byte array

4. Before converting the byte array to a string, you need to iterate over it and convert it as follows:

myByte.ToString("x2").ToLower()

Then you get MD5 hash code which is the same as PHP. Why it's such a hassle in.NET, and perhaps one of the reasons why so many developers are still passionate about PHP development, is that each programming language has its own charm and purpose!

Based on the above discussion, the complete code is as follows:
 
public static string MD5ForPHP(string stringToHash) 
{ 
var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); 
byte[] emailBytes = Encoding.UTF8.GetBytes(stringToHash.ToLower()); 
byte[] hashedEmailBytes = md5.ComputeHash(emailBytes); 
StringBuilder sb = new StringBuilder(); 
foreach (var b in hashedEmailBytes) 
{ 
sb.Append(b.ToString("x2").ToLower()); 
} 
return sb.ToString(); 
} 

Alternatively, you can write the above method as an C# extension method and simply modify the method signature.
 
public static string MD5ForPHP(this String, string stringToHash) 
{ 
// Your code here. 
} 

The PHP program and C# program involve conversion between formats in many ways, as well as conversion between date formats if PHP is running on a server of type UNIX. The following two methods show how to convert UNIX time to C# DateTime and how to convert C# DateTime to UNIX time.
 
public static DateTime UnixTimeStampToDateTime(long unixTimeStamp) 
{ 
// Unix timestamp is seconds past epoch 
DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); 
return dtDateTime.AddSeconds(unixTimeStamp); 
} 

public static long DateTimeToUnixTimeStamp(DateTime datetime) 
{ 
TimeSpan span = (datetime - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)); 
return (long)span.TotalSeconds; 
} 


Related articles: