As you know, MD5 is a very common hash algorithm which is usually used to encrypt the user’s password stored in database or verify data to ensure it’s not be changed in a complex transaction with multiple steps like online payment while transmit among parties.
In PHP, there is a built in function md5(string $str) which easily calculates the md5 hash of a string. However, with .Net Framework Web or Windows application, you have to write something to encrypt a string with MD5 hash algorithm.
Below is the MD5 function written in C#:
public string CreateMD5Hash(string RawData) { byte[] hash = System.Security.Cryptography.MD5.Create().ComputeHash(System.Text.Encoding.ASCII.GetBytes(RawData)); string str = ""; byte[] numArray = hash; int index = 0; while (index < numArray.Length) { byte num = numArray[index]; str = str + num.ToString("x2"); checked { ++index; } } return str; } |
Example and full source code
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class aspnet_csharp_md5 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Write(CreateMD5Hash("123456")); //Response: e10adc3949ba59abbe56e057f20f883e } public string CreateMD5Hash(string RawData) { byte[] hash = System.Security.Cryptography.MD5.Create().ComputeHash(System.Text.Encoding.ASCII.GetBytes(RawData)); string str = ""; byte[] numArray = hash; int index = 0; while (index < numArray.Length) { byte num = numArray[index]; str = str + num.ToString("x2"); checked { ++index; } } return str; } } |
You can verify the MD5 result via a Online MP5 Generator tool.