看了很多篇的文章,都是讲解如何调用System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(a,"MD5")来进行MD5加密。但是在ASP.NET4.5中,该方法已经过时,因此只能考虑到自己编写一个MD5方法来进行加密或者直接调用网上查找到的API。
- /// <summary>
- /// MD5加密
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static string Md5(string str)
- {
- // Create a new instance of the MD5CryptoServiceProvider object.
- MD5 md5Hasher = MD5.Create();
- // Convert the input string to a byte array and compute the hash.
- byte[] data = md5Hasher.ComputeHash(Encoding.GetEncoding("UTF-8").GetBytes(str));
- // return BitConverter.ToString(data);//可以直接使用这个方法
- // Create a new Stringbuilder to collect the bytes
- // and create a string.
- StringBuilder sBuilder = new StringBuilder();
- // Loop through each byte of the hashed data
- // and format each one as a hexadecimal string.
- for (int i = 0; i < data.Length; i++)
- {
- sBuilder.Append(data.ToString("x2"));
- }
- // Return the hexadecimal string.
- return sBuilder.ToString();
- }
- }