Recently in an existing system for C # transformation, the system was previously done with PHP, the backend administrator login with the MD5 encryption algorithm. In PHP, it is very simple to encrypt a string MD5, one line of code:
Copy Code code as follows:
MD5 ("Something you want to encrypt.")
Call the MD5 () method directly, and then pass the string that will be MD5 encrypted to get the hash code returned. In C # should also have a corresponding algorithm bar! Is that right? I first tried the following code, resulting in a hash code and PHP is not the same.
Copy Code code as follows:
public static string MD5 (String stringtohash)
{
Return FormsAuthentication.HashPasswordForStoringInConfigFile (Stringtohash, "MD5");
}
So, we had to borrow C # 's MD5CryptoServiceProvider object to write code to transform it.
1. Instantiate the MD5CryptoServiceProvider object
2. Convert a string to a byte array
3. Use the ComputeHash () method of the MD5CryptoServiceProvider object to encrypt the byte array, returning the converted byte array
4. Before you convert a byte array to a string, you also need to traverse it and do the following conversions:
Mybyte.tostring ("X2"). ToLower ()
Then, you can get the same MD5 hash code as PHP. Why in. NET is so troublesome, perhaps this is why so many developers are still enthusiastic about PHP development of one of the reasons, every programming language has its own charm, there is the significance of its existence!
Based on the above discussion, the complete code is as follows:
Copy Code code 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 a C # extension method, and only need to modify the method signature.
Copy Code code as follows:
public static string md5forphp (this string, string Stringtohash)
{
Your code here.
}
PHP and C # programs are in many ways related to the conversion between formats, if the server running PHP is UNIX type, there will also be a conversion between date formats. The following two methods show how to convert Unix time to C # datetime and how to convert C # datetime to Unix time.
Copy Code code as follows:
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;
}