机房合作—MD5加密密码
发布日期:2021-06-29 11:15:49 浏览次数:2 分类:技术文章

本文共 1335 字,大约阅读时间需要 4 分钟。

  我们知道注册用户时,用户的密码都存在数据库中了,但是都不是以明文存储的,这些数据库中的密码都是经过加密的。因为如果存储的是明文,一旦数据库被侵入,将会给用户带来巨大的损失,所以我们要对密码进行加密。

  在登录的时候,可以先将明文用加密算法转换成密文,然后再用密文和数据库中存储的密文进行比较,如果一致就说明密码正确,如果不一致密码自然也就不正确。下面我介绍两种用MD5算法加密的方法,不过第一种已经过时了,官方文档也推荐使用第二种。

第一种方法

  1. 首先引用 程序集

在这里插入图片描述
  2. 代码

//此种方法已过时using System.Web.Security;public string GetMD5(string source)  {      return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5");}

第二种

  这是官方文档中给出的方法:

public 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();}

  不知道大家还记不记得 string 和 StringBuilder 的区别?上面的方法中拼接字符时用的就是 StringBuilder 类。

  String 在运算时(如赋值、拼接等)会产生一个新的实例,而 StringBuilder 则不会。所以在对大量字符串拼接或频繁对某一个字符串进行操作时最好用 StringBuilder,不要使用 String。

在这里插入图片描述

转载地址:https://blog.csdn.net/zwj_jyzl/article/details/85227865 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:机房合作总结
下一篇:SVN学习

发表评论

最新留言

不错!
[***.144.177.141]2024年04月26日 21时41分47秒