利用MD5加密

原来使用的加密方法提示:"System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(string,string) 已过时"。

查看帮助文档关于md5的“Example”代码:

static string getMd5Hash(string input)
    {
        // Create a new instance of the MD5CryptoServiceProvider object.
        MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();

        // Convert the input string to a byte array and compute the hash.
        byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

        // 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[i].ToString("x2"));
        }

        // Return the hexadecimal string.
        return sBuilder.ToString();
    }

根据帮助文档修改成所需的方法代码:

 1  /// <summary>
 2         /// md5加密字符串
 3         /// </summary>
 4         /// <param name="source">要加密的源</param>
 5         /// <param name="md5">传入md5类的实现</param>
 6         /// <returns></returns>
 7         public static string ToMD5(this string source,MD5CryptoServiceProvider md5)
 8         {
 9             //md5加密;
10             //Encoding.UTF8.GetBytes(input) 把传入的字符串计算转换成utf8编码字节数组;
11             //创建一个md5实例,调用其ComputeHash计算指定的字节数组的哈希值;
12             byte[] data= md5.ComputeHash(Encoding.UTF8.GetBytes(source));
13             StringBuilder stringBuilder = new StringBuilder();
14             for (int i = 0; i < data.Length; i++)
15             {
16                 stringBuilder.Append(data[i].ToString("X2"));
17             }
18             return stringBuilder.ToString().Replace("-","");
19         }
ToMD5()

具体调用:

 1 [HttpPost,ValidateAntiForgeryToken]
 2         public ActionResult Login(FormCollection form)
 3         {
 4             if (ModelState.IsValid)
 5             {
 6                 string name,pwd;
 7                 using (MD5CryptoServiceProvider md5 =new MD5CryptoServiceProvider())
 8                 {
 9                     name = form["Email"];
10                     pwd = form["Pwd"].ToMD5(md5);
11                 }
12                
13                 if (CurrentContext.ServiceSession.UserInfoBLL.Where(o => o.UserName == name).Any())
14                 {
15                     if (CurrentContext.ServiceSession.UserInfoBLL.Where(o => o.UserName == pwd).Any())
16                     {
17                         return RedirectToAction("");
18                     }
19                 }
20             }
21             ModelState.AddModelError("", "用户名或密码错误");
22             return View();
23         }
View Code

 

posted on 2017-10-28 12:14  qt11  阅读(421)  评论(0)    收藏  举报

导航